Search code examples
jqueryparent-childclosesttoggleclass

JQuery Selecting closest parent a:link


I'm trying to toggle a CSS class for the closest parent a:link in a navigation menu based on the child sub-menu being hovered. I can get it to work for the closest parent <li> tag, but not the a:link inside which I want this event to occur for.

The HTML:

<ul class="menu">
  <li><a href="#">First Parent</a>
     <ul class="sub-menu">
          <li><a href="#">First Child</a></li>
          <li><a href="#">Second Child</a></li>
     </ul></li>
  <li><a href="#">Second Parent</a>
     <ul class="sub-menu">
          <li><a href="#">First Child</a></li>
          <li><a href="#">Second Child</a></li>
     </ul></li>
</ul>

So, the function I have written to select the parent <li> which is working is :

$("ul.sub-menu").hover(function(){
        $(this).closest("li").toggleClass("parenthovered");
});

but how can I get this class to toggle for the a:link of the parent in ul.menu li? Something like:

$("ul.sub-menu").hover(function(){
        $(this).closest("li a").toggleClass("parenthovered");
});   

but that of course does not work, I'm just not sure what syntax I need to change.

Many thanks SO.


Solution

  • $("ul.sub-menu").hover(function(){
        $(this).siblings('a').toggleClass("parenthovered");
    }); 
    

    DEMO