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
Written by David Christiandy
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Related Tags
#javascript
Did you know?
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#