javascript – how to add/remove css class from a dom element

To change css style of a dom element,we usually operate directly on the style property of the element.for example:

document.getElementById('Id'').style.visibility = "visible";

what if we don’t want to operate in this way,we need to apply a list of css rule to the element.in this case,we just need to specify a new css class for the element.

document.getElementById('Id'').class = "newClass";

The code above will not work at all.

document.getElementById('Id').className = "newClass";

The code above will set the className to newClass.To only add or remove,the code will be a little more:

Source code    
document.getElementById("MyElement").className += " MyClass";
Source code    
document.getElementById("MyElement").className =
   document.getElementById("MyElement").className.replace
      ( /(?:^|\s)MyClass(?!\S)/ , '' )

or we can just

Source code    
document.getElementById('id').classList.add('class');
document.getElementById('id').classList.remove('class');

One thought on “javascript – how to add/remove css class from a dom element

  1. hi all team,

    i have one problem to add class in ie 8, 7.
    but jquery addclass() not working so any solution is there for solve my pro.
    also i was used attr(‘class’,”) but it remove my class and replace class and also not working
    when i see in developer tool class not added.

    thanks.