Swati Sharma
Swati Sharma

Reputation: 709

How to add a class to the immediate children of an <li>?

<ul>
 <li><a href="">link 1</a></li>
 <li><a href="">link 2</a></li>
 <li><a href="">link 3</a>
   <ul>
    <li><a href="">link 1</a></li>
    <li><a href="">link 2</a></li>
   </ul>
 </li>
</ul>

How to add class to the immediate children 'a' of the LI, while on hover of the LI.

while i mouse out of the LI. the class should be removed.

I am trying to write following code for this.

$('.nice-menu li').mouseover(function(){
       $(this).children('a' , 'span a')
    }) ;  

Upvotes: 3

Views: 99

Answers (2)

jAndy
jAndy

Reputation: 236022

$('.nice-menu').find('li > a').bind('mouseenter', function(){
    $(this).addClass('whatsoever');
});

$('.nice-menu').find('li > a').bind('mouseleave', function(){
    $(this).removeClass('whatsoever');
});

or use the jQuery .hover() which actually does the exact same.

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630409

You can do this using .hover() and .toggleClass(), like this:

$('.nice-menu li').hover(function(){
   $(this).children('a' , 'span a').toggleClass('hoverClass');
});  

Note that the event bubbles though, so in the case of the nested links, the class will be toggled on both the parent and the children, but often you want to highlight the parent you're under in the menu, not sure that you do though, you can see what I mean here.

Upvotes: 4

Related Questions