Choosing Children but not grandchildren with Jquery

余生颓废 提交于 2019-12-22 10:24:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!