[英]Parents selector in jQuery
I need to get all elements whose n-th parent (ie elem.parent().parent()...parent()) has a specific class. 我需要获取其第n个父元素(即elem.parent()。parent()... parent())具有特定类的所有元素。 Is that possible?
那可能吗?
For example: 例如:
<div class="success">
<div id="depth-1">
<div id="depth-2">
<div>Return me</div>
<div>Return me</div>
</div>
</div>
</div>
the command with parent depth of 3 and class "success" will return the "Return me"
divs. 父深度为3且“成功”类的命令将返回
"Return me"
div。
You can use the Child selector as follows: 您可以使用子选择器,如下所示:
var returnMe = $(".success > * > * > *");
Although in your particular example I would probably do: 虽然在你的特定例子中我可能会这样做:
var returnMe = $(".success div div div");
I'm not sure about n-deep, but this will get all divs whose great-grand-parent (n = 3) has the class success
. 我不确定n-deep,但是这将获得所有div-grand-grand-parent(n = 3)的
success
。
$('.success > * > * > div')
You could write a function to generate the selector. 您可以编写一个函数来生成选择器。 Something like:
就像是:
function getNDeepSelector(n, className) {
var selector = '.' + className, ii;
for (ii = 0; ii < n; ii += 1) {
selector += ' > *'
}
return selector;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.