Skip to content Skip to sidebar Skip to footer

Remove Element By Tag Name

Possible Duplicate: use remove() on multiple elements I am trying to remove all elements that have a tag name of 'label'. I have the following code. It works to some degree, but

Solution 1:

var element = document.getElementsByTagName("label"), index;

for (index = element.length - 1; index >= 0; index--) {
    element[index].parentNode.removeChild(element[index]);
}

Solution 2:

The problem is that document.getElementsByTagName() returns a NodeList, not an Array. The content, and therefore length, of a NodeList is updated when you remove an element from the DOM that's in the NodeList. So when you remove the first element, the NodeList gets shorter and a new first element occupies index 0. Updating index in the loop therefore makes you miss at least one element, possibly more depending on the length of the result.

Try something like this:

var elements = document.getElementsByTagName('label')
while (elements[0]) elements[0].parentNode.removeChild(elements[0])

Solution 3:

When you remove the nodes from a document, the list of nodes that you just obtained from getElementsByTagName() gets updated too to avoid lingering references, so you should just keep removing the first node until none remain.

var nodes = document.getElementsByTagName("label");

for (var i = 0, len = nodes.length; i != len; ++i) {
    nodes[0].parentNode.removeChild(nodes[0]);
}

Here, the value of nodes.length is cached; otherwise it would keep decreasing and you end up only removing half :)

Solution 4:

The "problem" is that .getElementsByTagName() returns a Live NodeList. Hence, when you remove the head (first) entry, the tail fills up and moves to the left, so to speak.

Its not a real Javascript Array where this would work as expected. To create such a frozen Array we can go like

var element = Array.prototype.slice.call(document.getElementsByTagName("label"),0); 

for (var index = 0, len = element.length; index < len; index++) {
    element[index].parentNode.removeChild(element[index]);
}

Solution 5:

Why not use jQuery? Then it's simply

$("label").remove();

Post a Comment for "Remove Element By Tag Name"