Is there a better way to select grandparent elements in jQuery in order to avoid this ?
$(this).parent().parent().parent().parent().parent().children(".title, .meta").fadeIn("fast");
Thanks.
Is there a better way to select grandparent elements in jQuery in order to avoid this ?
$(this).parent().parent().parent().parent().parent().children(".title, .meta").fadeIn("fast");
Thanks.
In addition to
parents()
, as they've said, you should also check outclosest()
. Read the comparison in the documentation there, but its main differences are that it searches for only one result, and it includes$(this)
in what it searches (could get the thing you're searching from if you're not specific enough). Pros and cons.I wrote this simple plugin because I thought I had an unambiguous class selection somewhere giving me errors. Selecting grandparent seemed more direct than
$().parents()
for this particular case.Well, I used this once then realized I actually had a spelling error. Not sure how helpful it really is.
$('myelem').gparent(2);
gets you the grandparent of 'myelem'.@Femi had an answer to do this, and mentioned recursion, yet his solution was not recursive, here's a recursive jQuery solution for getting ancestors of an item:
If this is your HTML:
You can call
to get the grandparent of element
child
. Here's the JSFiddleYou can use the
parents()
method which matches parents against a selectorhttp://api.jquery.com/parents/
Or if you're using 1.4 there is a new
parentsUntil()
methodhttp://api.jquery.com/parentsUntil/
Use the
parents()
selector to get all parents of an element. You can then either search the collection, or iterate over it if you want to affect all ancestors.