How to remove div if img src is empty with javascript Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to remove div if img src is empty with javascript without wasting too much if your time.

The question is published on by Tutorial Guruji team.

Hi I am trying to figure out how to remove a div if the img src is empty.

I’ve searched on stackoverflow, but most are all jq based. Can someone help in vanilla javascript?

<div class="swiper-wrapper ">
      <div class="swiper-slide">
          <img
             src="https://images.unsplash.com/photo-1526947425960-945c6e72858f?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTN8fHByb2R1Y3RzfGVufDB8fDB8fA%3D%3D&w=1000&q=80"
             alt=""
             class="imgCard"
             color=""
           />
       </div>
       <div class="swiper-slide">
          <img
             src=""
             alt=""
             class="imgCard"
             color=""
           />
       </div>
</div>

Answer

Here how you can do this

const swipers = document.querySelectorAll('.swiper-slide');

swipers.forEach(e => {
  const imgSource = e.querySelector('img').getAttribute('src');
  if (imgSource.trim() === '') {
    e.remove()
  }
})
<div class="swiper-wrapper ">
  <div class="swiper-slide">
    <img src="https://images.unsplash.com/photo-1526947425960-945c6e72858f?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTN8fHByb2R1Y3RzfGVufDB8fDB8fA%3D%3D&w=1000&q=80" alt="" class="imgCard" color="" />
  </div>
  <div class="swiper-slide">
    <img src="" alt="" class="imgCard" color="" />
  </div>
</div>
We are here to answer your question about How to remove div if img src is empty with javascript - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji