javascript trying to remove all things with certain tags

后端 未结 2 1033
无人共我
无人共我 2021-01-23 05:19

I\'m trying to use javascript to remove everyhting with button or input tags from a page... So far my code removes some of them and I dont know why. It only removes one checkbox

2条回答
  •  没有蜡笔的小新
    2021-01-23 05:19

    document.getElementsByTagName returns a live NodeList. That means, when you remove the first element, a) the length decreases and b) the (first) item of the list is shifted.

    There are two possibilities to work around that:

    • always remove the last element. The NodeList is in document order, so that will work:

      for (var i=buttons.length-1; i>=0; i--) // var i=buttons.length; while(i--)
          buttons[i].parentNode.removeChild(buttons[i]);
      
    • always remove the first element, and don't run an index until the length:

      while (buttons.length) // > 0
          buttons[0].parentNode.removeChild(buttons[0]);
      

    It also would work with jQuery and co, because they copy the NodeList items in a static array. You can do that yourself as well:

    var staticButtons = Array.prototype.slice.call(buttons);
    for (var i=0; i

    or you use a document selection method that returns a static NodeList right away, like querySelector:

    var staticList = document.querySelectorAll("button, input");
    

提交回复
热议问题