Reputation: 4028
Can anybody explain why remove() method does not work as I expected. I want remove all img elements from the document. Loop through document and remove all images, that is what I want but this removes only 2 images,why? Here is the code JSBIN
HTML
<img src="http://www.lorempixel.com/50/50" alt="pic">
<img src="http://www.lorempixel.com/50/50/animals" alt="pic">
<img src="http://www.lorempixel.com/50/50/city" alt="pic">
JS
var imgElements = document.getElementsByTagName("img"); // HTMLCollection
for(var i=0; i<imgElements.length; i++) {
var img = imgElements[i];
img.remove();
}
Upvotes: 1
Views: 662
Reputation: 1074535
There are two things that worry me about that code:
remove
is a relatively new DOM method which isn't well-supported. For better support, use img.parentNode.removeChild(img);
getElementsByTagName
returns a live NodeList
, and so when you remove the elements from the beginning of the list, all the others shift up. So if the list has 5 entries, and you remove the i=0
element, all the others move and now there's a new i=0
element (and the length is 4
). Your loop will move on to i=1
and so the element at i=0
(which used to be at i=1
) won't get processed.
For a non-live NodeList
, use querySelectorAll('tagname')
(or just loop through the list backward, removing from the end). Or use Array.prototype.slice
to convert the NodeList
into an array.
querySelectorAll
is supported by all modern browsers, and also by IE8.
Here's an example using querySelectorAll
:
var imgElements = document.querySelectorAll("img"); // HTMLCollection
for(var i=0; i<imgElements.length; i++) {
var img = imgElements[i];
img.parentNode.removeChild(img);
}
Or just counting backward:
var imgElements = document.getElementsByTagName("img"); // HTMLCollection
for(var i=imgElements.length-1; i>=0; i--) {
var img = imgElements[i];
img.parentNode.removeChild(img);
}
Or using Array.prototype.slice
:
var imgElements = Array.prototype.slice.call(document.getElementsByTagName("img"));
for(var i=0; i<imgElements.length; i++) {
var img = imgElements[i];
img.parentNode.removeChild(img);
}
Upvotes: 6