0

I'm trying to use addEventListener on each li in side a list obtained from querySelectorAll, changing each item color as I hover the mouse over it. However I cannot change color by using the index of the item in the list but have to use this. I wonder why index doesnt work here

var lis = document.querySelectorAll("li");
for(var i = 0; i < lis.length; i++) {
   lis[i].addEventListener("mouseover", function() {
       this.style.color = "green";
    }); 
}

1 Answers1

0

You also need to use mouseout event. You can also use classList.add to add a class on mouseover & on mouseout use classList.remove which will remove the class

var lis = document.querySelectorAll("li");
for (var i = 0; i < lis.length; i++) {
  lis[i].addEventListener("mouseover", function() {
    this.classList.add("green");
  });

  lis[i].addEventListener("mouseout", function() {
    this.classList.remove("green");
  });
}
.green {
  color: green;
}
<ul>
  <li>1</li>
  <li>1</li>
  <li>1</li>
  <li>1</li>
  <li>1</li>
  <li>1</li>



</ul>
brk
  • 48,835
  • 10
  • 56
  • 78