Remove All Images

前端 未结 5 1701
长情又很酷
长情又很酷 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]);
    

提交回复
热议问题