To make the effect work separately for each class (Javascript)

There are three classes named "main-menu."
I want to apply the effect that underlines when I raise the mouse cursor in the area corresponding to each class.
I know that the current target is in the 0th index of the class and I have to use variables, but I don’t know how to change that to suit the situation.
I would appreciate it if you could tell me how to solve this problem.

enter image description here

window.onload = function(){
var target = document.getElementsByClassName("main-menu")[0];
target.addEventListener('mouseover', function(){
    target.style.borderBottom = "5px solid black";
});
target.addEventListener('mouseout', function(){
    target.style.borderBottom = "none";
});

}

7 thoughts on “To make the effect work separately for each class (Javascript)”

  1. You can use loop and add effect to each element. You can do this with css as well

    .main-menu:hover { border-bottom: 5px solid black; }

        window.onload = function(){
    var elements = document.getElementsByClassName("main-menu");
    
    for(let index=0; index < elements.length;index++) {
      const target = elements[index];
      target.addEventListener('mouseover', function(){
          target.style.borderBottom = "5px solid black";
      });
      target.addEventListener('mouseout', function(){
          target.style.borderBottom = "none";
      });
    })
    }
    Reply

Leave a Comment