How to remove a class from elements in pure JavaScript?

后端 未结 6 637
[愿得一人]
[愿得一人] 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.

提交回复
热议问题