Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript - understanding how css classes change / update

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 ;

  1. first delete the current className of the mydiv
  2. then assign the className (the code I have already mentioned in the function) )
like image 526
nimala9 Avatar asked Jun 15 '26 07:06

nimala9


1 Answers

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.

like image 119
RobG Avatar answered Jun 16 '26 20:06

RobG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!