I have a script that adds a video tag to a page. That bit works fine, but having added the video I want to add an event listener to the video tag, but it comes back as undefined. I’m assuming it’s because the additional HTML hasn’t yet been added. How do I wait till the video element exists?
const pv = document.querySelectorAll(".playVid"),
ib = document.getElementById("vidbox");
for (let j = 0; j < pv.length; j++) {
pv[j].addEventListener("click", function() {
let vid = this.dataset.vid;
fetch("getVideo.php?id=" + vid)
.then((response) => {
if (response.ok) return response;
throw Error(response.statusText);
})
.then((response) => response.text())
.then((text) => ib.innerHTML = text)
.catch((error) => console.log("There was an error:", error));
document.getElementById("infobox").className = "visible";
document.getElementById("boxHolder").style.display = "flex";
const v = document.getElementsByTagName("video")[0];
console.log(v); // undefined
})
};