Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove element by tag name [duplicate]

Tags:

javascript

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 it only removes 1 label. The other 5 still remain. How can I change the code to remove all "label" tags?

element = document.getElementsByTagName("label"); for (index = 0; index < element.length; index++) {     element[index].parentNode.removeChild(element[index]); } 
like image 705
Daniel Avatar asked Dec 22 '12 14:12

Daniel


2 Answers

var element = document.getElementsByTagName("label"), index;  for (index = element.length - 1; index >= 0; index--) {     element[index].parentNode.removeChild(element[index]); } 
like image 72
Tomalak Avatar answered Oct 08 '22 12:10

Tomalak


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]) 
like image 45
seliopou Avatar answered Oct 08 '22 13:10

seliopou