Removing HTML elements from a NodeList

1 February 2009

The Scenario

You have the following elements:


And now you want to remove them. Maybe you tried the following:

var spans = document.getElementsByTagName("span"),
l = spans.length;
for(var i = 0; i < l; i++) {

If you did, you probably failed, why? Because when you remove a element from the DOM, any reference to this element previously stored in a NodeList is also removed.

When the for loop reaches the 3:rd iteration there are only 2 items left in the spans NodeList and hence spans[3] is all of a sudden undefined.

The Solution

The solution is simply to iterate through the NodeList backwards.

while(l--) {

By doing this, you'll safely remove all span elements from the document

That is all.

Share on Twitter
Photo of me

Hi, thanks for reading!

Iā€™m Daniel, Software Engineer from Sweden. If you have any questions regarding this article please reach out to me on Twitter. You can also find me on GitHub.

Read more articles written by me: