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]); }
var element = document.getElementsByTagName("label"), index; for (index = element.length - 1; index >= 0; index--) { element[index].parentNode.removeChild(element[index]); }
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With