0

I have situation like that

<section>

    <div>On a hover change css here</div>

    <a>Hover me</a>

</section>

I want to change css of div when a is hovered.

Div have to be before a and there is no selector to select sibling that is before element.(related topic)

I also tried do do something like section:has(> a) >img but :has() selector has very weak browsers support. (related topic)

Is there any way to do this thing in only css or using simple js?

(Stack is telling me that this question has been answered in this topic so here is the difference: In this topic the question is about existance of previous sibling selector and the answers aren't much helpful in this situation and in my question I ask about how to do this in this specific situation)

Innarq
  • 17
  • 6

1 Answers1

1

The javascript is pretty straightforward. Give the anchor you want an id (I've called it 'hoverme')

<section>
  <div>On a hover change css here</div>
  <a id="hoverme">Hover me</a>
</section>

Add a class to cover styling the div (e.g. this)

<style>
  .hoverdiv {
    color:red;
  }
</style>

Then just add a couple of event listeners to the anchor at the window.onload event like this:

<script>
  window.addEventListener('load', (event) => {
    const anchor=document.querySelector('#hoverme');
    anchor.addEventListener('mouseover', (event) => {
      event.target.parentElement.querySelector('div').classList.add('hoverdiv');
    });
    anchor.addEventListener('mouseout', (event) => {
      event.target.parentElement.querySelector('div').classList.remove('hoverdiv');
    });
  });
</script>
Adam
  • 5,495
  • 2
  • 7
  • 24