I’m having difficulty targeting the child div of id="videoContainer"
and changing its style
<div id="videoContainer"> <div style="width: 640px; height: 360px"> <------- target this <video src="" preload="auto" autoplay="" style="width: 100%; height: 100%" ></video> </div> </div> const videoContainer = document.getElementById('videoContainer') document.getElementById('videoContainer').children?.[0]?.setAttribute("style", `width: 150px; height: 200px;`);
Advertisement
Answer
You can use querySelector with the direct child operator >
(and maybe first with :first-child
if you have more than one child div) like this:
const videoContainer = document.querySelector('#videoContainer > div') videoContainer.style.width = "150px" videoContainer.style.height = "200px" console.log("videoContainer width is", videoContainer.style.width)
/* what I think you need too */ #videoContainer video { object-fit: contain; }
<div id="videoContainer"> <div style="width: 640px; height: 360px"> <!------- target this --> <video src="//samplelib.com/lib/preview/mp4/sample-5s.mp4" preload="auto" autoplay="" style="width: 100%; height: 100%"></video> </div> </div>
object-fit: contain
will force you video to scale into its parent. You may want to use cover
or else. For more information, read simulate background-size:cover
on <video>
or <img>