0

My JS skills are failing me, and maybe also my Google skills. This is what I'm trying to do:

When an <li> is hovered in the .first division, add an ".active" class to the <li> in the .second division with the same ID. So if you hover over .first li#one, a class of .active would be added .second li#one.

Note: the IDs are dynamic and so can't be known in advance.

Here's what the html would look like:

<div class"first">
  
  <ul>
    <li id="one">Lorem</li>
    <li id="two">Ipsum</li>
    <li id="three">Dolor</li>
  </ul>
  
</div>

<div class="second">

  <ul>
    <li id="one">Lorem</li>
    <li id="two">Ipsum</li>
    <li id="three">Dolor</li>
  </ul>
  
</div>
  

I don't think there's a pure CSS solution, but of course that would be even better.

Anyone looking to do this with classes instead of IDs, here's the edited snippet from the below answer:

document.querySelectorAll("nav.primary li").forEach(li => {
  li.addEventListener("mouseover", e => {
    document.querySelectorAll(`.${e.target.classList}`)[1].classList.add("active");
  });
  li.addEventListener("mouseout", e => {
    document.querySelectorAll(`.${e.target.classList}`)[1].classList.remove("active");
  });
});
Josh M
  • 131
  • 1
  • 7
  • I know IDs shouldn't be duplicated. I just meant this as an example, but maybe I could simplify things by making the ids in the second div slightly different. For example, id="second-one", id="second-two", and etc. Terrible naming, I know. – Josh M Aug 04 '22 at 18:16

1 Answers1

1

So there are CSS solutions for things like this, such as this post.

However, because you said you won't know the IDs of the elements in advance, JavaScript seems like a fair choice. I'm not saying it's impossible with CSS, but my solution uses JavaScript.

Basically you can loop through all of the <li> elements contained within the first class and apply two event listeners. One for mouseover and one for mouseout (hover). From here, the script selects the second instance of an element with the same id and adds or removes a class active.

document.querySelectorAll(".first ul li").forEach(li => {
  li.addEventListener("mouseover", e => {
    document.querySelectorAll(`#${e.target.id}`)[1].classList.add("active");
  });
  li.addEventListener("mouseout", e => {
    document.querySelectorAll(`#${e.target.id}`)[1].classList.remove("active");
  });
});
.active { background: #CCC; }
<div class="first">
  
  <ul>
    <li id="one">Lorem</li>
    <li id="two">Ipsum</li>
    <li id="three">Dolor</li>
  </ul>
  
</div>

<div class="second">

  <ul>
    <li id="one">Lorem</li>
    <li id="two">Ipsum</li>
    <li id="three">Dolor</li>
  </ul>
  
</div>
EssXTee
  • 1,783
  • 1
  • 13
  • 18