Brian Barthold
Brian Barthold

Reputation: 1623

menu find a child of li element with jQuery

What I need to add a class on hover to the a tag with a menu below is the menu. Any ideas?

<ul id="nav">
<li><a href="">Home</a></li>
<li><a href="">Another</a>
<ul>
<li><a href="">Sub</a></li>
...

$("#nav li ul li a").hover(
    function() {
         $(this).parent().parent().parent().addClass('current');

    },
    function() {
        $(this).parent().parent().parent().removeClass('current');      
        //alert();          
    }
);

Upvotes: 2

Views: 829

Answers (4)

hunter
hunter

Reputation: 63522

$("#nav a").hover(
    function() { $(this).closest("a").addClass("current"); },
    function() { $(this).closest("a").removeClass("current"); }
);

Upvotes: 3

chrisl-921fb74d
chrisl-921fb74d

Reputation: 23110

Might but just quicker to do this

$(document).ready(function() {
    $('#nav a:hover').parents('div > ul > li:hover > a').addClass('current');
});

Upvotes: 0

rterrani
rterrani

Reputation: 526

This method is what you need http://api.jquery.com/closest/ god bless jQuery

Upvotes: 0

Greg
Greg

Reputation: 21909

You can achieve this without jQuery by using css psuedo classes. All elements in html gain a psuedo class of :hover when the mouse is over them.

To select them in CSS:

#nav li ul li:hover {
    // Your style here.
}

Upvotes: 1

Related Questions