When I want to get, for example, the 3rd level parent of the element I must write $(\'#element\').parent().parent().parent()
Is there a more optimal method for
you can also use :
$(this).ancestors().eq(n)
ex: $(this).ancestors().eq(2)
-> the parent of the parent of this
.
You could give the target parent an id or class (e.g. myParent) and reference is with $('#element').parents(".myParent")
Depends on your needs, if you know what parent your looking for you can use the .parents() selector.
E.G: http://jsfiddle.net/HenryGarle/Kyp5g/2/
<div id="One">
<div id="Two">
<div id="Three">
<div id="Four">
</div>
</div>
</div>
</div>
var top = $("#Four").parents("#One");
alert($(top).html());
Example using index:
//First parent - 2 levels up from #Four
// I.e Selects div#One
var topTwo = $("#Four").parents().eq(2);
alert($(topTwo ).html());
using eq appears to grab the dynamic DOM whereas using .parent().parent() appears to grab the DOM that was initially loaded (if that is even possible).
I use them both on an element that has classes applied it to on onmouseover. eq shows the classes while .parent().parent() doesnt.
You could use something like this:
(function($) {
$.fn.parentNth = function(n) {
var el = $(this);
for(var i = 0; i < n; i++)
el = el.parent();
return el;
};
})(jQuery);
alert($("#foo").parentNth(2).attr("id"));
http://jsfiddle.net/Xeon06/AsNUu/
It's simple. Just use
$(selector).parents().eq(0);
where 0 is the parent level (0 is parent, 1 is parent's parent etc)