jQuery: Selecting only the first level children

By blobaugh, June 22, 2010 10:50 am
Views: 0

Using the .not() operator with jQuery it is possible to select only the first level of children of an element. This could come in handy on a menu for instance. Let's see what the menu code looks like.

 
<ul>
<li>Item
<ul>
<li>Sub</li>
<li>Sub2</li>
<li>Sub3</li>
</ul>
</li>
<li>Item2</li>
<li>Item3</li>
</ul>
 

We are trying to get ul li, but not ul li ul li. jQuery has a brilliant method to select page elements like so:

 
$('ul li')
 

However this will get ALL of the li elements not matter the depth. We only want the first level of li. Luckily jQuery again has a method to accomplish this using .not()

 
$('ul li').not('ul li ul li')
 

Voila! We now have only the first level of li elements

2 Responses to “jQuery: Selecting only the first level children”

  1. sissi says:

    you can do this much easier:

    $(‘ul’).children(‘li’)

  2. blobaugh says:

    sissi,

    Very true, however that will also return the sub ul as well. Using the .not() I was able to grab only the text in the first child, and not continue on down the tree.

Leave a Reply

Theme by Blam Designs
Based on Themocracy