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.
JavaScript
x
22
22
1
let videos = ["video 1","video 2"];
2
let current_video = undefined;
3
window.onload = function () {
4
function update_video(video) {
5
// loops through all of my h2 elements to change their style to default
6
for(var i = -1 ; i < videos.length ; i++) {
7
document.getElementById(String("vid-"+i)).style.color = "#ca6735";
8
document.getElementById(String("vid-"+i)).style.textDecoration = "none";
9
}
10
// sets the selected h2 element (using a button to select it) to a new color with an underline.
11
current_video = Number(video);
12
document.getElementById(String("vid-"+video)).style.color = "#49a1b6";
13
document.getElementById(String("vid-"+video)).style.textDecoration = "underline";
14
}
15
document.getElementById("vid-bt-0").addEventListener("click", function() {
16
update_video(0);
17
});
18
document.getElementById("vid-bt-1").addEventListener("click", function() {
19
update_video(1);
20
});
21
}
22
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:
JavaScript
1
5
1
for(var i = 0; i < videos.length ; i++) {
2
document.getElementById(String("vid-"+i)).style.color = "#ca6735";
3
document.getElementById(String("vid-"+i)).style.textDecoration = "none";
4
}
5