zero01alpha zero01alpha - 11 months ago 54
CSS Question

jQuery addClass() method adds class, but does not change css style

I am using the jQuery

function to make the background color of a text input field red to signify an error. Here is my code


$("#id").delegate("input:text", "keyup change", function(e) {
val = $(this).val();
if (condition) {
$(this).addClass("error"); // This doesn't work
//$(this).css("background-color", "#ff8080"); // This Works

} else {
$(this).removeClass("error"); // This doesn't work
//$(this).css("background-color", ""); // This Works



.error {
background-color: #ff8080;

I inspect the element and it does indeed add and remove the error class, but it does not actually change the color like it should. If I use the
method to change the color, then it works just fine, but I would like to avoid that.

Answer Source

This will most likely be a case of the priority of the CSS stylings added.

Out of the two of these, the first adds a new class. A class will have a priority within all of the classes added to the element, so if another class is added after this then that background color will override the error class.

The second option adds an inline style to the element, which takes priority over all of the classes added, and so will change the colour.

$(this).addClass("error"); // This adds a class element which can be overwritten
//$(this).css("background-color", "#ff8080"); // This adds an inline style.


.error {
    background-color: #ff8080 !important;

Or find out which class is overwriting the error class and then change that background colour.