How to remove a class from elements in pure JavaScript?

后端 未结 6 600
[愿得一人]
[愿得一人] 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:13

    It's 2020... keep it simple.

    Times have changed and now the cleanest and most readable way to do this is:

    Array.from(document.getElementsByClassName('widget hover')).forEach((el) => el.classList.remove('hover'));
    

    If you can't support arrow functions then just convert it like this:

    Array.from(document.getElementsByClassName('widget hover')).forEach(function(el) { 
        el.classList.remove('hover');
    });
    

    Additionally if you need to support extremely old browsers then use a polyfil for the forEach and Array.from and move on with your life.

    0 讨论(0)
  • 2020-11-30 03:15

    Find elements:

    var elements = document.getElementsByClassName('widget hover');
    

    Since elements is a live array and reflects all dom changes you can remove all hover classes with a simple while loop:

    while(elements.length > 0){
        elements[0].classList.remove('hover');
    }
    
    0 讨论(0)
  • 2020-11-30 03:16

    Given worked for me.

    document.querySelectorAll(".widget.hover").forEach(obj=>obj.classList.remove("hover"));
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-30 03:35

    This might help

    let allElements = Array.from(document.querySelectorAll('.widget.hover'))
    for (let element of allElements) {
      element.classList.remove('hover')
    }
    
    0 讨论(0)
  • 2020-11-30 03:40

    elements is an array of DOM objects. You should do something like this

    for (var i = 0; i < elements.length; i++) {
       elements[i].classList.remove('hover');
    }
    

    ie: enumerate the elements collection, and for each element inside the collection call the remove method

    0 讨论(0)
提交回复
热议问题