How can I replace one class with another on all elements, using just the DOM?

后端 未结 2 1298
感情败类
感情败类 2020-12-01 15:15

I just want to change a classname to another one.

I\'ve tried using

document.getElementsByClassName(\"current\").setAttribute(\"class\", \"none\");

2条回答
  •  执笔经年
    2020-12-01 15:45

    document.getElementsByClassName("current") returns a HTMLCollection, not an HTMLElement. You can access elements in the list the same way you would access an array.

    The following will change the class of the first element in the HTMLCollection.

    document.getElementsByClassName("current")[0].setAttribute("class", "none");
    

    However, you do not have to use the setAttribute method, you can just set the className property of the element.

     element.className = 'none';
    

    Please note that HTMLCollection are live, wich means that as soon as the element will not have the current class name anymore, the element will be removed from the array, so to avoid any issues you could iterate over it using the following approach:

    var list = document.getElementsByClassName("current");
    
    while (list.length) {
        list[0].className = 'none';
    }
    

提交回复
热议问题