Search code examples
jquerycss-selectorschildren

Choosing Children but not grandchildren with Jquery


I have a nested unordered list like so:

<ul id="parent">
   <li>
      <ul> <!-- select this-->
        <li></li>
        <li>
            <ul>
                <li></li>
            </ul>
        </li>
      </ul>
   <li>
</ul>

I need to select the children of #parent but not the grandchildren.

$(#parent).children('ul'); selects all children, including grandchildren. How do I limit this to just children?


Solution

  • $('#parent').children('>ul');
    

    The above would not work with the markup in the question.

    You want the child selector

    You'd need the following:

    $('#parent > li > ul');