-1

I have a scenario when on hover of child element, I want to append a style to the parent element. My code can be seen below, as well as here:

html:

  <body>
    <div>
      <span>hover</span>
    </div>
  </body>

scss:

 span:hover{
   div{
     border:1px solid red;
   }
 }

On hovering over the child text, I need to set the border for the parent div. But it isn't happening that way. Any help would be appreciated.

Angelos Chalaris
  • 6,611
  • 8
  • 49
  • 75
tania saxena
  • 173
  • 1
  • 2
  • 16

2 Answers2

1

One cannot simply traverse up the DOM in CSS. You will need to use JavaScript or jQuery.

Here is an article explaining why: http://snook.ca/archives/html_and_css/css-parent-selectors

TLDR, it's due to the way CSS is read by the browser, and if we were to traverse up the DOM, it would increase the performance hit by a factor of ten (at least!), because it would need to read every single node multiple times to see whether or not it fits the profile. Hence, it's simply not viable.

Javascript way

document.getElementById("child").onmouseover = function() {
  this.parentNode.style.border = "1px solid red";
}
<body>
  <div id="parent">
    <span id="child">hover</span>
  </div>
</body>

jQuery way

$("#child").hover(function() {
  $(this).parent().css("border", "1px solid red");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <div id="parent">
    <span id="child">hover</span>
  </div>
</body>
nashcheez
  • 5,067
  • 1
  • 27
  • 53
0

$(function() {
  $("div span").hover(function() {
    $(this).parents('div').toggleClass("myClass");
  });
})
.myClass{
border:1px solid #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <span>hover</span>
</div>
ani_css
  • 2,118
  • 3
  • 30
  • 73