javascript trying to remove all things with certain tags

后端 未结 2 1007
无人共我
无人共我 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<staticButtons.length; i++)
        staticButtons[i].parentNode.removeChild(staticButtons[i]);
    

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

    var staticList = document.querySelectorAll("button, input");
    
    0 讨论(0)
  • 2021-01-23 05:27
    var checkboxes = document.getElementsByTagName("input");
    for (var j = 0; j < buttons.length ; j++) // You use the wrong variable here
    {
        checkboxes[j].parentNode.removeChild(checkboxes[j]);
    }
    

    Should be;

    for (var j = 0; j < checkboxes.length ; j++) 
    

    Regarding to the undeleted button, maybe it's because it's an input type="button" and not a <button>?

    Note that document.getElementsByTagName("input"); will get and delete later all the inputs, not just the checkboxes!


    May I suggest you using a javascript library like jQuery? you could have done this will one line of code with no problems:

    $('input[type="button"], input[type="checkbox"], button').remove();
    
    0 讨论(0)
提交回复
热议问题