Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

285
Views
jQuery: style hover on parents() and children()

I am wondering if it is possible to change the style of child when its element was hovered, while its css was also styled when its parent was hovered?

To make my question clear, I wrote down a basic code below:

   //styling child while mouse is inside child element
$('child').on('hover', function(e){
   if (e.type == 'mouseenter'){
      $(this).css('background','yellow');
   }
})

   // styling child while mouse is inside parent
$('child').parents().on('hover', function (e){
   if (e.type == 'mouseenter'){
      $(this).css('background', 'blue');
   }
})

So, basically once user enters space of parent to make child's bg blue, and once it enters space of child to change from blue to yellow bg.


I saw a comment on why I do not use css, so this is a little explanation: I am unable to select parent element. I can only do it from child using parents(). And as long as css does not support parents() method yet I went with jquery. :)

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

CSS Alone:

div {
  padding: 20px;
  border: 1px solid black;
}

/* something hovered that have .child as direct child => change .child color to blue */
*:hover > .child {
  background-color: blue;
}

/* .child element hovered => override the above color and set it to yellow (note that the above rule is still taking effect when this is taking effect) */
.child:hover {
  background-color: yellow;
}
<div>
  PARENT
  <div class="child">CHILD</div>
</div>
<div>
  PARENT
  <div class="child">CHILD</div>
</div>
<div>
  PARENT
  <div class="child">CHILD</div>
</div>

about 4 years ago · Santiago Trujillo Report

0

is that the behaviour you expect ?

$('#child').parent().on('mouseover', function(e){
  if(this===e.target){
    $(this).children().css('background','blue');
  }else{
    $(this).children().css('background','yellow');
  }
}).on('mouseout', function(e){      
    $(this).children().css('background', 'green');
});
#parent{
  width:200px;
  height:100px;
  background-color:#f00;
}

#child{
  width:30px;
  height:30px;
  background-color:green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
  <div id="child"></div>
</div>

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!