Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleaner way to write element.parent().parent().parent().parent().parent()

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();
like image 824
Silver Light Avatar asked Jan 12 '11 20:01

Silver Light


2 Answers

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.

like image 153
user113716 Avatar answered Oct 16 '22 03:10

user113716


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);
like image 36
Rion Williams Avatar answered Oct 16 '22 02:10

Rion Williams