I need to get all elements whose n-th parent (ie elem.parent().parent()...parent()) has a specific class. 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.
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
.
$('.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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.