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

3 thoughts on “jQuery: Selecting only the first level children

  1. sissi (August 13, 2010)

    you can do this much easier:

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

  2. blobaugh (August 13, 2010)

    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.

  3. Mirel (October 20, 2015)

    This is best solution:

    $(‘pre > ul > li’)