Whether to choose all, but not children

I have this code:

$li = $("li", this) 

Which selects all li in my code. This works fine, but I want $li exclude li that are in the submenu.

  <ul id="navigation"> <li><a href="#">blah 1</a></li> <ul id="subnav"> <li><a href="#">sub 1</a></li> <li><a href="#">sub 2</a></li> <li><a href="#">sub 3</a></li> </ul> </li> <li><a href="#">blah 2</a></li> <li><a href="#">blah 3</a></li> <li><a href="#">blah 4</a></li> <li><a href="#">blah 5</a></li> </ul> 

So $li will only refer to blah, not sub.

I thought it was something like:

 $li = $("li", this).parents() 

But that does not do what I want.

+7
jquery
source share
4 answers

Just use the child selector > :

 $("#navigation > li") 
+19
source share

You want to use the immediate child selector, > :

 $li = $('#navigation > li'); 
+13
source share
 var li = $("#navigation > li"); 

> selects only direct children

+4
source share

Future googlers may find this answer useful if they are here (for example, I) are looking for Choose all without any children

 $("#mylist li:not(:has(ul))") 

or

 $("#mylist li:not(:has(li))") 
0
source share

All Articles