javascript Jquery 查找类型的第一个直接子代
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22117483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery Find first direct child of a type
提问by Malharhak
I am looking for a way to find the first direct child of an element, of a precise type.
我正在寻找一种方法来查找元素的第一个精确类型的直接子元素。
Let's imagine this markup:
让我们想象一下这个标记:
<div id="mainDiv">
<div id="otherDiv">
<p> Stuff </p>
</div>
<p> Stuff 2 </p>
<p> Stuff 3 </p>
</div>
So here, what I want to get is "Stuff 2" the first paragraph to be a direct child.
所以在这里,我想要得到的是“Stuff 2”第一段成为直系子。
If using jquery I do something like $('#mainDiv').find('p:first');
I will get the paragraph inside the first div.
如果使用 jquery,我$('#mainDiv').find('p:first');
会在第一个 div 中获取段落。
What I need is to ignore nested childs and take only the first direct one. How should I do that?
我需要的是忽略嵌套的孩子,只采取第一个直接的。我该怎么做?
回答by adeneo
Use the direct descendant selector >
使用直接后代选择器 >
$('#mainDiv > p:first')
or even children()
甚至 children()
$('#mainDiv').children('p').first()