What JavaScript will remove all image tags?
The previous answer will only remove every second image.
Remember NodeLists returned by getElementsByTagName or other DOM methods are ‘live’. That means when you remove image 0, images 1–n move down to 0–(n-1); this is a ‘destructive iteration’.
To avoid this, either make a static Array copy of the NodeList (as the jQuery answer is effectively doing), or, faster, just iterate the list backwards:
for (var i= document.images.length; i-->0;)
document.images[i].parentNode.removeChild(document.images[i]);
This should work too:
var images = document.getElementsByTagName('img');
while(images.length > 0) {
images[0].parentNode.removeChild(images[0]);
}
With jQuery:
$("img").remove();
UPD: sorry, this is a wrong answer, see comments. This is a correct answer.
Something like this:
images = document.getElementsByTagName('img');
for (i = 0; i < images.length; i++) {
images[i].parentNode.removeChild(images[i]);
}
OR a slight modification of my first attempt to answer this question:
var images = document.getElementsByTagName('img');
var l = images.length;
for (var i = 0; i < l; i++) {
images[0].parentNode.removeChild(images[0]);
}
Without using external libraries:
var images = document.getElementsByTagName('img');
for(var i=0; i < images.length; i++) {
images[i].parentNode.removeChild(images[i]);
}
Or using jquery:
$('img').remove();