One embodiment, el.setAttribute ( 'class', 'a');
.a{ color: red; } #id box var box = document.getElementById('box'); box.setAttribute('class','a');
IE6 / 7: div background color is not red
IE8 / 9/10 / Firefox / Safari / Chrome / Opera: div background color is red
Results: IE6 / 7 do not support setAttribute ( 'class', 'xxx') provided element class.
Second way, el.setAttribute ( 'className', 'a');
.a{ color: red; } #id box var box = document.getElementById('box'); box.setAttribute('className','a');
IE6 / 7: div background color is red
IE8 / 9/10 / Firefox / Safari / Chrome / Opera: div background color is not red
Results: IE8 / 9/10 / Firefox / Safari / Chrome / Opera does not support setAttribute ( 'className', 'xxx') provided element class.
Note: The above two methods are compatibility issues
Three ways, el.className = 'abc'; (good compatibility)
.a{ color: red; } .b{ font-size: 18px; } #id box var box = document.getElementById('box'); box.className = 'a'; box.className + = 'B'; // white space before
Results: All browsers support.
In addition there are other ways
Use el.classList add and delete class
.a{ color: red; } .b{ font-size: 18px; } .c{ background: #8A2BE2; } #id box var Box = document.getElementById ( 'Box' ); // the console.log (box.classList); box.classList.add ( 'A'); // add box.classList.remove ( 'B'); // remove box.classList.toggle ( 'C') // if there is a corresponding class is deleted, it is not added var if_b box.classList.contains = ( 'a'); // Finding no corresponding class, returns true / to false the console.log (if_b);