Remove All Images

前端 未结 5 1593
长情又很酷
长情又很酷 2020-12-13 11:06

What JavaScript will remove all image tags?

相关标签:
5条回答
  • 2020-12-13 11:27

    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]);
    
    0 讨论(0)
  • 2020-12-13 11:28

    This should work too:

    var images = document.getElementsByTagName('img');
    while(images.length > 0) {
        images[0].parentNode.removeChild(images[0]);
    }
    
    0 讨论(0)
  • 2020-12-13 11:37

    With jQuery:

    $("img").remove();
    
    0 讨论(0)
  • 2020-12-13 11:44

    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]);
    }
    
    0 讨论(0)
  • 2020-12-13 11:48

    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();
    
    0 讨论(0)
提交回复
热议问题