skip to Main Content

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.

2

Answers


  1. Looks like an issue with the indexing on the while loop. If you have a condition that i should keep increasing whilst it is smaller than or equal to the array length. You end up with the last value of i being the array length.

    If you have arr=[‘a’,’b’,’c’], the indices or [0,1,2] and arr.length is 3. So arr[arr.length] is arr[3] which is undefined.

    In this case should be while (i < heading.length) so you stop the loop when i equals the index of the last element.

    Login or Signup to reply.
  2. 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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search