I am trying to use a while loop to change the background-color of some h1‘ s.
I know that there can be only one H1 on the page but is not what i am try to practice.
The code that I wrote works but when I open the console I still get an error.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>While loop</title>
<style>
.red{
color:red
}
</style>
</head>
<body>
<h1 class="red">heading01</h1>
<h1>heading02</h1>
<h1 class="red">heading03</h1>
<h1>heading04</h1>
<h1 class="red">heading05</h1>
<script>
function changeColor(){
const heading = document.querySelectorAll("h1");
let i = 0;
while (i <= heading.length){
if (!heading[i].classList.contains("red")){
heading[i].style.backgroundColor = "lightgreen";
}
i++;
}
}
changeColor();
</script>
</body>
</html>
index1.html:27 Uncaught TypeError: Cannot read properties of undefined (reading 'classList') at changeColor (index1.html:27:25) at index1.html:34:5
Can anyone tell me why it is giving me that error?
Thank you.
I tried to go step by step with a console.log() to see what is happening.
Also I tried it with a For Of loop and that works with no errors.
>Solution :
The error is
while (i <= heading.length){ ... }
instead of
while (i < heading.length){ ... }
In almost every programming languages, array indexes starts with 0 and this is the case with JS.
If you console.log the array of headings you will see that you have 5 elements identified with indexes from 0 to 4
NodeList(5) [ h1.red, h1, h1.red, h1, h1.red
]
0: <h1 class="red">
1: <h1 style="background-color: lightgreen;">
2: <h1 class="red">
3: <h1 style="background-color: lightgreen;">
4: <h1 class="red">
length: 5