My goal is to dynamically load videos on the page after it has fully loaded. I have a script that successfully works in Firefox and Chrome, but I encounter errors when using Edge/IE. The specific error message I receive is SCRIPT5007: Unable to get property 'append' of undefined or null reference. This error points to the line where I set the id attribute of the iframe element based on the 'youtube' attribute retrieved from the HTML. The main issue is that the iframe is not being appended to the page, hence the videos are not being displayed. On CodePen, the error indicates Unable to get property 'src' of undefined or null reference, emphasizing the same problem of the iframe not being appended. I have tried various approaches like using v[n].attr() or changing it to data-youtube and accessing it with v[n].dataset.youtube, but none of these methods seem to work in Edge.
Check out the working version on Firefox/Chrome on CodePen
<section data-grid="container stack-2" class="m-multi-feature f-align-center" id="m-multi-tiles">
<section data-grid="container">
<ul role="tablist">
...
...
... (The HTML content continues here)
...
...
</ul>
</section>
//lazy load youtube videos
document.addEventListener("DOMContentLoaded",
function() {
var div, n,
v = document.getElementsByClassName("youtube-player");
for (n = 0; n < v.length; n++) {
var iframe = document.createElement("iframe");
var embed = "https://www.youtube.com/embed/ID?showinfo=0";
iframe.setAttribute("src", embed.replace("ID", v[n].dataset.id));
iframe.setAttribute("frameborder", "0");
iframe.setAttribute("allowfullscreen", "1");
iframe.id = v[n].attributes['youtube'].value;
v[n].append(iframe);
console.log(v[n].getAttribute('youtube') + 'youtube');
}
});
// Function to reveal lightbox and add YouTube autoplay
function revealVideo(div, video_id) {
var video = document.getElementById(video_id).src;
document.getElementById(video_id).src = video + '&autoplay=1';
document.getElementById(div).style.display = 'block';
}
// Hiding the lightbox and removing YouTube autoplay
function hideVideo(div, video_id) {
var video = document.getElementById(video_id).src;
var cleaned = video.replace('&autoplay=1', '');
document.getElementById(video_id).src = cleaned;
document.getElementById(div).style.display = 'none';
}