How to remove a class from elements in pure JavaScript?

后端 未结 6 640
[愿得一人]
[愿得一人] 2020-11-30 03:07

I would like to know how to select all elements with class names \"widget\" and \"hover\" and then remove class \"hover\" from these elements.

I have the following J

6条回答
  •  忘掉有多难
    2020-11-30 03:35

    var elems = document.querySelectorAll(".widget.hover");
    
    [].forEach.call(elems, function(el) {
        el.classList.remove("hover");
    });
    

    You can patch .classList into IE9. Otherwise, you'll need to modify the .className.

    var elems = document.querySelectorAll(".widget.hover");
    
    [].forEach.call(elems, function(el) {
        el.className = el.className.replace(/\bhover\b/, "");
    });
    

    The .forEach() also needs a patch for IE8, but that's pretty common anyway.

提交回复
热议问题