0
var AddressesList = document.getElementsByTagName("li");
for (var i = 0; i < AddressesList.length; i++){
    var allow = true;
    AddressesList[i].addEventListener("click", function() {
        if (allow == true) {
            AddressesList[i].style.backgroundColor = 'red';
            allow = false;
        }
    })
}

I keep getting the error:

Uncaught TypeError: Cannot read properties of undefined (reading 'style')

I have some idea that referencing an array element inside the event listener returns undefined? Because when I try just printing the array element, I get undefined, but it works outside the event listener. What's the issue and how do I fix it

  • Add your HTML please – Yarin Levi Apr 30 '22 at 18:49
  • `for (let i = 0; ...` and it will work. With `var`, all of your click handlers end up with `i` being equal to `AddressesList.length`, which points to a non-existing array index. Even better, don't use index-based looping at all. Instead use `for (const Address of AddressesList) { ... }`. – connexo Apr 30 '22 at 18:57

1 Answers1

-1

Its working this way

var AddressesList = document.getElementsByTagName("li");

for (let i = 0; i < AddressesList.length; i++) {
  const element = AddressesList[i];

  var allow = true;
  element.addEventListener("click", function () {
    if (allow) {
      element.style.backgroundColor = "red";
      allow = false;
    }
  });
}
<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
  </head>

  <body>
    <div id="app">
      <ul>
        <li>Inder</li>
        <li>Jane Doe</li>
        <li>John Doe</li>
      </ul>
    </div>

    <script src="src/index.js"></script>
  </body>
</html>
Inder
  • 1,711
  • 1
  • 3
  • 9
  • You never modify `allow`. Also the problem is OP using `var` instead of `let` in the for-loop. – connexo Apr 30 '22 at 19:00
  • @connexo Missed it before. I've added the line for modifying allow. – Inder Apr 30 '22 at 19:04
  • @connexo modifying allow depends on the use case of OP, if they want to change background color of every li or only one. – Inder Apr 30 '22 at 19:06