Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
2
rated 0 times [  5] [ 3]  / answers: 1 / hits: 123207  / 11 Years ago, thu, july 25, 2013, 12:00:00

I want to add CSS attributes to my element, but my current solution loses all previous attributes that had an impact on the element.


function checkNr(id) {
var value = document.getElementById(id).value;
if (parseFloat(value) == NaN) {
document.getElementById(id).setAttribute("style", "border:2px solid red; background-color: rgb(255, 125, 115);");
}
else {
document.getElementById(id).setAttribute("style", "border:default; background-color: rgb(255, 255, 255);");
}
}

Before using this method the element already had the attributes:


float: left;
width: 50px;

Afterwards, the element loses these attributes, leaving only the specific attributes from the JavaScript method. So, I want to add attributes without replacing them.


More From » html

 Answers
10

Setting the style attribute like that, overwrites the attribute and removes previously set styles.



What you really should do is set the styles directly instead by changing the style property :



function checkNr(id) {
var elem = document.getElementById(id),
value = elem.value;
if (parseFloat(value) == NaN) {
elem.style.border = '2px solid red';
elem.style.backgroundColor = 'rgb(255, 125, 115)';
} else {
elem.style.border = 'none';
elem.style.backgroundColor = 'rgb(255, 255, 255)';
}
}

[#76752] Wednesday, July 24, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bryonk

Total Points: 161
Total Questions: 116
Total Answers: 107

Location: Albania
Member since Sun, Nov 22, 2020
4 Years ago
bryonk questions
;