How to remove all elements of a certain class from the DOM?

后端 未结 4 784
有刺的猬
有刺的猬 2020-11-29 06:34



        
4条回答
  •  春和景丽
    2020-11-29 06:45

    [].forEach.call(document.querySelectorAll('.hi'),function(e){
      e.parentNode.removeChild(e);
    });
    

    Here I'm using Array.prototype.forEach to easily traverse all elements in an array-like object, i.e. the static NodeList returned by querySelectorAll, and then using removeChild() to remove the item from the DOM.

    For older browsers that don't support querySelectorAll() or forEach():

    var classMatcher = /(?:^|\s)hi(?:\s|$)/;
    var els = document.getElementsByTagName('*');
    for (var i=els.length;i--;){
      if (classMatcher.test(els[i].className)){
        els[i].parentNode.removeChild(els[i]);
      }
    }
    

    Note that because getElementsByTagName returns a live NodeList, you must iterate over the items from back to front while removing them from the DOM.

    There are also some older browsers that don't support querySelectorAll but that do support getElementsByClassName, which you could use for increased performance and reduced code.

提交回复
热议问题