我有几个.video-wrapper div,我想确保在定位.video-wrapper和视频标记之前有一个嵌套的HTML5视频标记。
虽然下面的代码对我来说看起来很简单,但似乎我花了好几个小时试图来这里。
是否有更好或更快或更标准的循环方式来检查是否存在嵌套元素而不是下面的方法来确定长度是否> 0?
我似乎错过了一些东西,而不是根据长度确定它是否存在。
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
}
}
答案 0 :(得分:2)
只需使用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>
答案 1 :(得分:0)
将querySelectorAll与css选择器一起使用。
var results = document.getElementById('results'),
videos = document.querySelectorAll('.videos video');
for (video of videos) {
results.insertAdjacentHTML('afterbegin', `<p>${video.id}</p>`);
}
&#13;
<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>
&#13;