conflictingresults conflictingresults - 1 month ago 14
HTML Question

JS targeting nested divs which contain video

I am trying to target a video element nested inside a div which has an id that I can set plus another div which has no id. What would be a smooth approach to targeting the video element and simply playing the video.

here is a sample of the nesting i am looking at.

<div id="vid1">
<div>
<video poster="poster_img.png" >
<source src="video.mp4" type="video/mp4">
</video>
</div>
</div>


Would you recommend childNodes, querySelector or another pathing?

Using JS I want to be able to say, vid1.play();
but these have all failed

document.getElementById('vid_1').childNodes[0].getElementsByTagName('video');
document.getElementById('vid_1').childNodes[0].querySelector('video');


Thanks all for your help.

Answer

Use document.querySelector with PARENT CHILD selector

Also note you had typo in vid_1, in markup it is vid1

console.log(document.querySelector('#vid1 video'));
//---------------------------------^^^^^^^^^^^^^^
<div id="vid1">
  <div>
    <video poster="poster_img.png">
      <source src="video.mp4" type="video/mp4">
    </video>
  </div>
</div>

Comments