Add CSS attributes to element with JavaScript

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)";
    }
}

Leave a Comment