If I need to select 10-th parent, is there a cleaner way, then repeating .parent() 10 times?
$('#element_id').parent().parent().parent().parent().parent().parent().parent().parent().parent().parent();
If there's a selector that represents the target you're after, then use .closest()
or .parents()
.
$('#element_id').closest('.someClass');
$('#element_id').parents('.someClass:first');
...but both of these will return the first match found. The proper solution will depend on your actual HTML markup.
(Note that .closest()
also evaluates the original element, while parents()
starts with the first ancestor.)
Also keep in mind that browsers make HTML corrections. So if you're traversing from inside a <table>
that has no <tbody>
to an element outside the <table>
, doing x number of .parent()
may give different results in different browsers.
The following post here uses this implementation:
jQuery.fn.getParent = function(num) {
var last = this[0];
for (var i = 0; i < num; i++) {
if(!last) break;
last = last.parentNode;
}
return jQuery(last);
};
// usage:
$('#myElement').getParent(3);
so your usage would simply be:
$('#element_id').getParent(10);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With