JS how to simplify

Basicly if I hover over a list item, I want to add a class to the corresponding span.
Now I’ve found how to do this with the following code.

My question: Is there a way to simplify this (without repeating)? If so, how exactly?

  var listItems = document.querySelectorAll(".hover");
  var spanClass = document.querySelectorAll(".navbar-top-border");


  listItems[0].addEventListener("mouseover", event => {
    spanClass[0].classList.add("navbar-top-border-visible");
  });
  listItems[0].addEventListener("mouseout", event => {
    spanClass[0].classList.remove("navbar-top-border-visible");
  });

  listItems[1].addEventListener("mouseover", event => {
    spanClass[1].classList.add("navbar-top-border-visible");
  });
  listItems[1].addEventListener("mouseout", event => {
    spanClass[1].classList.remove("navbar-top-border-visible");
  });

89 thoughts on “JS how to simplify”

Leave a Comment