Skip to content Skip to sidebar Skip to footer

Javascript Trying To Remove All Things With Certain Tags

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 out

Solution 1:

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();

Solution 2:

document.getElementsByTagName returns a liveNodeList. 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");

Post a Comment for "Javascript Trying To Remove All Things With Certain Tags"