user3893613
user3893613

Reputation: 181

How to determine if multiple divs have a nested tag

I have several .video-wrapper divs that I want to make sure have a nested HTML5 video tag in them before targeting both the .video-wrapper and the video tag.

While the code below looks really simple to me now, it seems like I've spent hours trying to get here.

Is there a better or faster or more standard way to loop through to check if nested elements exist rather than the approach below to determine if length > 0 ?

It just seems like I'm missing something rather than determining if it does or doesn't based on length.

var videoWrappers= document.getElementsByClassName("video-wrapper");
for (var i = 0; i < videoWrappers.length; i++) {
     var thisVideo = videoWrappers[i].getElementsByTagName('video')
      if(thisVideo.length > 0){
        // then the VIDEO tag exists 
        }else{ 
        // no video tag exists so exit loop
      }
  }

Upvotes: 0

Views: 104

Answers (2)

colecmc
colecmc

Reputation: 3318

Use querySelectorAll with a css selector.

var results = document.getElementById('results'),
    videos = document.querySelectorAll('.videos video');

for (video of videos) {
    results.insertAdjacentHTML('afterbegin', `<p>${video.id}</p>`);
}
<div id="results"></div>

<div class="videos">
  <a href="some-link.html">some link</a>
  <video id="myvid" width="400" controls>
    <source src="mov_bbb.mp4" type="video/mp4">
    <source src="mov_bbb.ogg" type="video/ogg">
    Your browser does not support HTML5 video.
  </video>
</div>

<div class="videos">
  <a href="some-link-1.html">some random link</a>
  <video id="myvid-1" width="400" controls>
    <source src="mov_bbb1.mp4" type="video/mp4">
    <source src="mov_bbb1.ogg" type="video/ogg">
    Your browser does not support HTML5 video.
  </video>
</div>

<div class="videos">
  <a href="some-link-2.html">some other link</a>
  <video id="myvid-2" width="400" controls>
    <source src="mov_bbb2.mp4" type="video/mp4">
    <source src="mov_bbb2.ogg" type="video/ogg">
    Your browser does not support HTML5 video.
  </video>
</div>

<div class="videos">
  <a href="no-video.html">No Video</a>
</div>

Upvotes: 0

baao
baao

Reputation: 73241

Simply select only those tags that match your condition using querySelectorAll()

document.querySelectorAll('.wrapper > video');

console.log(document.querySelectorAll('.wrapper > video')); 
<div class="wrapper">

</div>
<div class="wrapper">
  <video></video>
</div>
<div class="wrapper">

</div>

Upvotes: 2

Related Questions