问题
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')
来源:https://stackoverflow.com/questions/18195883/choosing-children-but-not-grandchildren-with-jquery