Last Updated: February 25, 2016
·
468
· davidchristiandy

Javascript's getElementsByClassName Gotcha's

<div class=“box”>1</div>
<div class=“box”>2</div>
<div class=“box”>3</div>

Let's say I want to output the innerHTML value, and then delete each box from the DOM.

with getElementsByClassName, we can easily do:

var boxes = document.getElementsByClassName(‘box’);
for(var i=0; i<boxes.length; i++) {
    console.log(boxes[i].innerHTML);
    boxes[i].parentNode.removeChild(boxes[i]);
}

Gotcha! This, sadly, will not work. The output:

1
3
ERROR

The reason is that when boxes[0] (first box) is deleted, that node is also deleted from from the variable boxes. So, the first element of boxes is now the second box.

Now, since the array auto-updates itself, the way to do this is:

while(boxes.length) {
    console.log(boxes[0].innerHTML);
    boxes[0].parentNode.removeChild(boxes[0]);
}

Reference: http://stackoverflow.com/a/15562532/1266558