Use jQuery to find the first parent element
I have run across this problem a few times lately and I thought I would write a post here as a way of remembering how to do it.
So you are doing some DOM Scripting and you want to find the first parent element that has a particular class. I have been using jQuery a lot lately and I initially thought this would be easy:
$('#test').parents('.parent-element');
However, as you notice with the example below you get all the parent elements with the specified class. So all we need to do now is filter out just the first element, like so:
$('#test').parents('.parent-element').filter(':first');
Done and done, see some example code to show it in action: Use jQuery to find the first parent element
I hope someone else finds this useful.
Technorati Tags: jQuery, JavaScript, Web, Example








February 24th, 2009 at 8:42 pm
Turns out that there is a parent() method. That makes it much easier!
September 10th, 2009 at 2:00 am
can’t you just use .parent() inplace of .parents()?
September 10th, 2009 at 2:01 am
oh you already added that. cheers.
August 24th, 2010 at 2:34 pm
@tappas, @James, you cannot user parent() because it “only travels a single level up the DOM tree” according to docs and my tests (which is most likely not what the author wants to do).
November 10th, 2010 at 6:06 pm
I know this is way old, but wanted to put this out there for anyone (like myself) who is may stumble on this in the future.
Use closest();
http://api.jquery.com/closest/
March 9th, 2011 at 5:10 pm
Thank you for advice, it works great!
September 8th, 2011 at 5:35 pm
Use this one
$(’currentelement’).cloesest(’div’);
This will select div as parent.
uuu
October 12th, 2011 at 11:29 pm
window.location=’:-)’;
November 3rd, 2011 at 12:43 pm
parents() will traverse the DOM all the way up and return every element that matches the selector. So even though you’re using filter() to trim out the other results, you’re actually searching for them all, not just the first.
closest() on the other hand will traverse upwards until it finds a single result, and only return that. in the case of what you’re trying to do, it’s much more efficient.
December 3rd, 2011 at 12:16 am
Ravinder Tulsiani (Parent Central: Advice & Tips Blog for Parents)…
[…]Use jQuery to find the first parent element | James Oppenheim’s blog[…]…