Kat Roz Kat Roz - 1 year ago 77
Javascript Question

JS can't delete all images from page

I'm trying to delete all images from page. The page is in HTML. This is my HTML button:

<input id="clickMe" type="button" value="Delete Images" onclick="click();" />

And the function is:

<script type="text/javascript">
function click(){
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {

All elements are tagged "img"

Answer Source

Removing a child can only be done from the parent:

function removeImages() {
  var images = [].slice.call(document.getElementsByTagName('img'), 0); // get the images as array like object, and turn it into an array using slice

  images.forEach(function(img) { // iterate the images array
    img.parentNode.removeChild(img); // remove the child node via the parent node
<button type="button" onclick="removeImages()">Remove Images</button>

  <img src="http://static.wixstatic.com/media/60d837_94f714500a3145a1b98efd7a6fe78ce7~mv2_d_3456_3456_s_4_2.jpg_256" />

  <img src="https://static-s.aa-cdn.net/img/ios/442131982/82d94c67fc3d8eb87e07d9bb568c5d4d?v=1" />

  <img src="https://pbs.twimg.com/profile_images/625769159339737088/2dwpQAXA.jpg" />


You can also use img.remove() instead of the cumbersome img.parentNode.removeChild(img), but it won't work in IE - see ChildNode.remove() on MDN.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download