Using the getAttribute method in Edge with JavaScript

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';
}

Answer №1

After some trial and error, I managed to make it work using iframe.setAttribute('id', v[n].getAttribute('youtube')); although I can't pinpoint why this method works while v[n].attributes['youtube'].value does not.

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.setAttribute('id', v[n].getAttribute('youtube'));
            v[n].appendChild(iframe);
        }
    });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

bridging information from tables with text fields in forms

I am working on an HTML/CSS page that utilizes a table layout filled with buttons to mimic a T9 keypad design. Within the page, I have a form containing two text fields. My aim is to populate these text fields with numbers based on the values from the tab ...

Issue with jQuery's JSON data not being properly transmitted to CodeIgniter (`

Based on my observation, the script provided below seems to be functioning properly: <script type="text/javascript" language="javascript"> $(document).ready(function() { $('#add').bind('keypress', function(e) { if(e.k ...

Issue with the Z-Index property not functioning as expected on unordered lists within a dropdown menu

I have a dropdown menu that opens to the left, but it is displaying underneath the content. I attempted adjusting the z-index of the content to 1 and the dropdown to 2, however, this did not resolve the issue. Here is a sample in jsFiddle: https://jsfiddl ...

Encountering an endless loop while attempting to retrieve data from Firebase in Next.js through the use of useEffect

Currently, I am in the process of setting up a video section for a project using NextJS. The videos are stored in firebase storage. I have implemented a dynamic route that retrieves all videos from a specific reference within the bucket. For instance, if ...

Creating an anonymous component in Vue.js involves enclosing the received slots (vnodes) within a wrapper component

Is there a way to wrap two specified named slots, slotOne and slotTwo, which are located in the child component at this.$scopedSlots.slotOne and this.$scopedSlots.slotTwo respectively? I would like to then conditionally render these slots (vnodes) as shown ...

Using jquery to update a link when a different link is clicked

Recently, I've started using JQuery and encountered a challenge. When I click on the first link, an Ajax request is sent to the server and data is received successfully. However, in the callback function, I'm struggling to change the display text ...

Troubleshooting problems with sending data in Jquery Ajax POST Request

I've spent a considerable amount of time searching for a solution to why my post request isn't sending its data to the server. Oddly enough, I can successfully send the request without any data and receive results from the server, but when attemp ...

Using Nest JS to create two instances of a single provider

While running a test suite, I noticed that there are two instances of the same provider alive - one for the implementation and another for the real implementation. I reached this conclusion because when I tried to replace a method with jest.fn call in my ...

Discovering the method to retrieve a previous month's date within a VueJs application using Javascript

Can someone guide me on how to retrieve the date of the past month using Vue? This is the code I currently have: import SomeTable from "./table/SomeTable"; export default { name: "Cabinets", components: {SomeTable}, data() { return { ...

Executing a callback function in AngularJS after dynamically rendering elements with `ng-repeat`

Many posts demonstrate how to implement callback functions in directives to wait for ng-repeat to finish before calling a function. Here is an example: <div ng-repeat="Object in Objects" class="objectClass" on-finish-render>{{Object.Overlay}</div ...

What exactly do bootstrap, javascript, jquery, and ajax entail?

Exploring the world of client-side scripting to enhance web page dynamism and data collection has piqued my interest. I have come across programming languages like JavaScript, Ajax, and jQuery. However, uncertainty clouds my understanding as concepts remai ...

Modify session variable upon link click

Here is an extension of the question posed on Stack Overflow regarding creating a new page for different PHP ORDER BY statements: Create a new page for different php ORDER BY statement? The task at hand requires changing a session variable and refreshing ...

How can JavaScript be utilized to disable the use of the spacebar?

I have implemented a live search feature on the website I'm working on. Currently, the search function queries the MySql database as soon as the first character is entered and updates the results with each subsequent character input. However, I'v ...

Unable to save cookies using AngularJs

Currently, I am immersed in a small project utilizing AngularJs. The main objective of this project is to save a user's username and password within browser cookies. Here is my snippet from app.js where you can observe ngCookies being injected as a d ...

Div Randomly Transforms Its Vertical Position

After successfully creating a VS Code Extension for code completion, I decided to develop a website as a landing page where users can sign up and customize their extension settings. The editor I built pops up first on the page seemed to be working fine in ...

Positioning an anchor element over an image in Internet Explorer (IE)

Encountering an issue with IE9 (and 8) involving the positioning of empty anchor elements over an image. The anchors contain text, which is pushed off the page using CSS's text-indent property. Currently working on a website with promo panels display ...

Guide to downloading a CSV file directly from a webpage built with vue.js

Delving into the world of vue.js, I find myself pondering over how to incorporate a download link in my webpage for a CSV file stored locally. In my component Template.vue, I have the following structure: <a :href="item.loc" download> {{item.title ...

The functionality of using an Ajax call to invoke a php function on the same page is not functioning correctly

I am facing an issue where Ajax is not working in the same PHP file as the PHP function I want to call. My goal is to have a button that, when pressed, will trigger the function without reloading the page. I have placed my Ajax script at the bottom and the ...

Is there a way to upload a file using express/multer without triggering a redirect?

Note: Despite coming across this post, I couldn't find it helpful. Other related posts were focused on angular/react, which are not relevant to my current project. I have implemented a file upload feature that should provide a response indicating whe ...

Virtual machines have encountered issues when attempting to utilize setTimeout within the browser with vm.runInNewContext

When running a JS script using the vm module in a browser, the following details are included: vm.runInNewContext(codeToEval, sandboxObject); Although interval methods like setTimeout and setInterval do not work, even when exposed in the sandboxObject cr ...