jQuery jQuery选择第一个“级别”上的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1112428/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:42:12  来源:igfitidea点击:

jQuery select elements on 1st "level"

jquerydomcss-selectors

提问by cletus

I want to select only the elements on the first "level".

我只想选择第一个“级别”上的元素。

Ex:

前任:

<div id="BaseElement">
  <p>My paragraph 0</p>
  <div>
    <span>My Span 0</span>
    <span>My Span 1</span>
  </div>
  <span>MySpan 2</span>
  <span>MySpan 3</span>
  <p>My paragraph 1</p>
</div>

Let's say that you got the BaseElement node.

假设您获得了 BaseElement 节点。

var Element = $("div#BaseElement");

How do I fetch nodes from only the base element node?

如何仅从基本元素节点获取节点?

$("div#BaseElement span")

should only result in getting MySpan 2 and MySpan 3.

应该只会导致获得 MySpan 2 和 MySpan 3。

回答by cletus

$("#BaseElement").children("span");

or

或者

$("#BaseElement > span");

See jQuery selectorsand children().

请参阅jQuery 选择器children().

回答by Jon Erickson

In the jQuery API, when it refers to 'descendants' it means all levels, and when it refers to 'children' it means only the first level

在 jQuery API 中,当它提到“后代”时,它意味着所有级别,当它提到“孩子”时,它仅意味着第一级

this will get you all first level children (in your example the first p, div, 2 spans, and last p)

这将为您提供所有第一级孩子(在您的示例中,第一个 p、div、2 个跨度和最后一个 p)

$('#BaseElement > *')

回答by barryku

Also refer to What is the difference direct descendent (>) vs. descendant in jQuery selectors?for differences between space and >in selectors. With space equals to find() and >equals to children(). In other words, the following pairs are equivalent,

另请参阅jQuery 选择器中的直接后代 (>) 与后代有何区别?选择器中空格和>之间的差异。空间等于 find() 而>等于 children()。换句话说,以下对是等价的,

$("#BaseElement").children("span");
$("#BaseElement > span");

Get all children plus their descendants:

获取所有孩子及其后代:

$("#BaseElement").find("span");
$("#BaseElement span");