3

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>
1
  • 1
    You can probably use an if statement like this: !HTMLImageElement.src. If it's empty, then change the div display style to none like this: HTMLDivElement.style.display = 'none'. Commented Jan 20, 2022 at 6:18

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

Comments

1

You can get all images which are child of .swiper-slide class and check if their have src attribute different than an empty string like this

let imgs = document.querySelectorAll(".swiper-slide img");

imgs.forEach(item => {
  if (item.getAttribute('src') === "") {
    item.parentNode.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="First image alternate text" class="imgCard" color="" />
  </div>
  <div class="swiper-slide">
    <img src="" alt="Second image alternate text" class="imgCard" color="" />
  </div>
</div>

1 Comment

You need to trim the source also, as there may be a chance that it contains space there which will not be empty

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.