Javascript - understanding how css classes change / update

I have a div with id = "mydiv", it is not assigned to the class at the beginning. The next two functions assign classes to mydiv.

function one(){
document.getElementById(mydiv).setAttribute("class", "classone");
}

function two(){
document.getElementById(mydiv).setAttribute("class", "classtwo");
}

      

After completing these two functions, what is the className mydiv? Is it classtwo or is it classone and classtwo both? (If it is both classes - how can I change function two to;

  • first remove the current class name mydiv
  • then assign the class name (the code I already mentioned in the function))
+3


source to share


2 answers


After completing these two functions, what is the className mydiv? Is it classtwo or classone and classtwo both?

This will be "classtwo". Have you checked it?

If it's both classes ...

This is not the case, 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 add class value, use:

document.getElementById(mydiv).className += " classtwo";

      

pay attention to the leading space. And remove all class values:

document.getElementById(mydiv).className = "";

      

There is also a WHATWG classList API which is also documented on MDN , however support may not be available in some browsers, so it is not safe to use it on the public web.

+2


source


Without using jQuery addClass

, etc., and if you don't want or cannot use classList

, you can handle it yourself with something like:

function addClass(elt, cls) {
    elt.className += " " + cls;
}

      

This comes with the risk of adding the same class twice, which does no harm but is inelegant. To avoid this problem:



function addClass(elt, cls) {
    var classes = elt.className.split(/\s+/),
        index = classes.indexOf(cls);

    if (index === -1) {
        elt.className = classes.concat(cls).join(' ');
    }
}

      

Similar logic can be used to implement removeClass

:

function removeClass(elt, cls) {
    var classes = elt.className.split(/\s+/),
        index = classes.indexOf(cls);

    if (index !== -1) {
        classes.splice(index, 1);
        elt.className = classes.join(' ');
    }
}

      

+1


source







All Articles