Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

There is no parent and before sibling css selector so what I'm supposed to do?

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading