Skip to content
Advertisement

Error code “Uncaught TypeError: Cannot read property ‘style’ of null” in my javascript code

I am using a for(){} statement to loop through every element I have in order to change the text color and remove underlining when a function is called. After doing so, the function will then set the font color and underline the selected text. However, I keep receiving the error message Uncaught TypeError: Cannot read property 'style' of null. I triple-checked My element’s names, making sure that they were right. They were.

let videos = ["video 1","video 2"];
let current_video = undefined;
window.onload = function () {
    function update_video(video) {
        // loops through all of my h2 elements to change their style to default
        for(var i = -1 ; i < videos.length ; i++) {
            document.getElementById(String("vid-"+i)).style.color = "#ca6735";
            document.getElementById(String("vid-"+i)).style.textDecoration = "none";
        }
        // sets the selected h2 element (using a button to select it) to a new color with an underline.
        current_video = Number(video);
        document.getElementById(String("vid-"+video)).style.color = "#49a1b6";
        document.getElementById(String("vid-"+video)).style.textDecoration = "underline";
    }
    document.getElementById("vid-bt-0").addEventListener("click", function() {
        update_video(0);
    });
    document.getElementById("vid-bt-1").addEventListener("click", function() {
        update_video(1);
    });
}

The code above is what I have currently. The code underneath the second comment works.

Advertisement

Answer

I guess because of i = -1 in for loop the problem occurs:

So, try with the below code:

        for(var i = 0; i < videos.length ; i++) {
            document.getElementById(String("vid-"+i)).style.color = "#ca6735";
            document.getElementById(String("vid-"+i)).style.textDecoration = "none";
        }
Advertisement