hatched
hatched

Reputation: 865

JS - Remove all <img> inside a div

I have a div that only contains images.

 <div class="content">
    <img src="img.png"/>
    <img src="img.png"/>
    <img src="img.png"/>
    <img src="img.png"/>
</div>

And I need to remove all <img> within the div.

With jquery , it can be done by

$('.content img').remove(); 

But how do I achieve this with only JavaScript?

Upvotes: 2

Views: 1598

Answers (2)

manas kumar
manas kumar

Reputation: 31

var images = document.getElementsByTagName('img');
for(var i=0; i < images.length; i++) {
    images[i].parentNode.removeChild(images[i]);
}

Hope this will work for you

Upvotes: 2

Hassan Imam
Hassan Imam

Reputation: 22534

You can select all img elements and then use remove() to removes the images from the DOM.

document.querySelectorAll(".content img")
  .forEach(img => img.remove());
<div class="content">
  <img src="img.png" />
  <img src="img.png" />
  <img src="img.png" />
  <img src="img.png" />
</div>

Upvotes: 4

Related Questions