1

I have created 8 divs with the class div.

<div class="div"></div>

Then I have created a function, removeDivs() to remove each div.

function removeDivs() {
    divs = document.getElementsByClassName('div')
    for (i = 0; i <= 8; i++) {
        divs.removeChild(divs.childNodes[i])
    }
}

Why doesn't this work?

JSFIDDLE: https://jsfiddle.net/nu8jt766/

1 Answer 1

6

It's not working because the .removeChild() method only removes the child node based on the parent element that the method is operating on. In your example, divs is an array-like object of elements (not the parent element of the current element you are iterating over), which means that nothing is being removed.

You need to select the parent element of the current .div element that you're iterating over and then remove the corresponding child.

In other words, change the following:

divs.removeChild(divs.childNodes[i]);

to:

divs[i].parentNode.removeChild(divs[i]);

As a side note, you will notice that the for loop has also been updated to decrement (rather than increment) since .getElementsByClassName() returns a live HTML collection that is updated when each element is removed (which means that you would skip over half of the elements if you increment).

Working Snippet:

function removeDivs() {
    divs = document.getElementsByClassName('div');
    for (var i = divs.length - 1; i > -1; i--) {
        divs[i].parentNode.removeChild(divs[i]);
    }
}

removeDivs();
.div { height: 100px; width: 100px; border: 2px solid #000; display: inline-block; }
<p>Nothing should be displayed</p>
<div class="div"></div><div class="div"></div><div class="div"></div><div class="div"></div><div class="div"></div><div class="div"></div><div class="div"></div><div class="div"></div>

Sign up to request clarification or add additional context in comments.

2 Comments

Why it does not work with for (var i = 0; i < divs.length; i++) { ?
@RayonDabre I updated my answer. It's because the method .getElementsByClassName() returns a live HTML collection of elements that is updated when each element is removed (which means that you would skip over elements if you increment).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.