Choosing Children but not grandchildren with Jquer

2019-05-26 17:51发布

问题:

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?

回答1:

$('#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');


回答2:

Children method should do the trick. Are you sure you're getting grandchildren?. You selector should actually return 0.

This code should do what you're looking for

$('#parent>li').children('ul')

From official documentation

Given a jQuery object that represents a set of DOM elements, the .children() method allows us to search through the children of these elements in the DOM tree and construct a new jQuery object from the matching elements. The .children() method differs from .find() in that .children() only travels a single level down the DOM tree while .find() can traverse down multiple levels to select descendant elements (grandchildren, etc.)



回答3:

put > before ul;

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


回答4:

Modify your original selector: $('#parent > li > ul')