jQuery: Selecting only the first level children

June 22, 2010

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.

  • Item
    • Sub
    • Sub2
    • Sub3
  • Item2
  • Item3

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