Ryan
Ryan

Reputation: 1791

How to find the direct child using this selector?

I have this little code:

$("ul#mainnav > li").hover(function(){
   $("ul#mainnav > li > a").slideUp();
})

I just don't know the right syntax for selecting the direct child <a> using $(this) What I used is this, and I think its wrong...

$(this).find("> a")

Thank you.

Upvotes: 2

Views: 271

Answers (2)

Justin Grant
Justin Grant

Reputation: 46683

For starters, you have an extra quote. Remove the quote after this. Like this:

$(this).find("> a") 

Admittedly I've never used selectors for this case, so I can't comment about why it's not working. Instead, I'd recommend using children() which is usually faster and, IMHO, clearer.

$(this).children('a'); 

But if you really want to use a string selector, this should work:

$('> a', this)

Note that the jquery docs say that the latter code will be deprecated at some point, so use with caution. I'd still recommend using children().

Upvotes: 2

Gregg B
Gregg B

Reputation: 13727

You can use $(this).children("a:first") if you just want the first a tag as well

Upvotes: 1

Related Questions