This question has already been answered:

There is a js code that takes an element by id (tried and by class) adds a class to it at mouseenter. The question is as follows: the code changes the first element that came to it with such an id (classo'm, although I have more than 5), how to change ALL these elements?

var one = document.querySelector('.img1'); one.addEventListener('mouseenter',function add() { one.classList.add("changes"); }); one.addEventListener("mouseleave",function remove(){ one.classList.remove("changes"); }); 
 <div class="blockOne"><img class="img1" src="home/1.png"></div> <div class="blockTwo"><img class="img1" src="home/2.png"></div> 

Reported as a duplicate at Grundy. javascript Jan 2 at 12:13 pm

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • If I'm not mistaken, document, getElementsByClassName ('classname') - an array with elements should be returned, and then whatever you want, do it with them. And what about id, in principle, you cannot create elements with the same id. Unless, of course, my memory serves me. - Sonic Myst
  • jQuery or loop, and not by id but by class. Id must be unique for each item. - Vladimir Klykov
  • The message was corrected, the code attached the situation is the same, the first element with the class img1 is changed, and the next is no longer. If I cut out the first one, the second one changes, but it’s necessary for what element I induced, that one changed - Nikita
  • You do not need to copy the answer in the body of the question, you need to mark the answer accepted by clicking on the check mark under it. - Enikeyschik

1 answer 1

 document.querySelectorAll('.img1').forEach(function(item) { item.addEventListener('mouseenter', function() { this.classList.add("changes"); }); item.addEventListener("mouseleave", function() { this.classList.remove("changes"); }); }); 
 .changes { background: lightgreen; } 
 <div class="blockOne"><img class="img1" src="home/1.png" alt="1.png"></div> <div class="blockOne"><img class="img1" src="home/2.png" alt="2.png"></div> 

  • Can you please explain this moment: forEach (item => .. - Nikita
  • @Nikita In this case, this is the same as forEach(function(item) { . - Igor