I have a div with id="mydiv" it is not assigned to a class at the beginning. The following two functions assign classes to the mydiv.
function one(){
document.getElementById(mydiv).setAttribute("class", "classone");
}
function two(){
document.getElementById(mydiv).setAttribute("class", "classtwo");
}
After these two functions are completed what is the className of mydiv? Is it classtwo or classone and classtwo both? (If it is both classes - how can I change function two to ;
After these two functions are completed what is the className of mydiv? Is it classtwo or classone and classtwo both?
It will be "classtwo". Did you check?
If it is both classes…
It isn't, the previous value is replaced by the new one. As pointed out in the comments, if you just want to replace the value it's easier to use the className property:
document.getElementById(mydiv).className = "classone";
and to add a class value, use:
document.getElementById(mydiv).className += " classtwo";
note the leading space. And to remove all class values:
document.getElementById(mydiv).className = "";
There is also a WHATWG classList API that is also documented at MDN, however support may be lacking in some browsers so not safe to use on the general web yet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With