I think, therefore I am. I am, therefore I sail

jQuery: Selecting only the first level children

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


PHP: Recursively convert an object to an array


PHP+Apache: Enabling XSS for iPhone apps with PhoneGap and jQTouch


  1. you can do this much easier:


  2. 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

    This is best solution:

    $(‘pre > ul > li’)

Powered by WordPress & Beards