I want to find the nth parent element of an given element and access the attributes of parent.
-
You can use .parents()
and .eq()
:
$('#element1').parents().eq(2);
http://jsfiddle.net/infernalbadger/4YmYt/
讨论(0)
-
use:
$('#element1').closest('#parent1');
讨论(0)
-
parents() returns a list, so this works:
$('#element1').parents()[2];
讨论(0)
-
You could make a little plugin to take care of that:
$.fn.nthParent = function(n){
var p = this;
for(var i=0;i<n;i++)
p = p.parent();
return p;
}
and then use it as:
$('#element1').nthParent(3);
讨论(0)