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: , , ,

Bookmarks:
  • Digg
  • Technorati
  • del.icio.us
  • Ma.gnolia
  • Reddit
  • Netscape
  • StumbleUpon
  • NewsVine

3 Responses to “Use jQuery to find the first parent element”

  1. James Oppenheim Says:

    Turns out that there is a parent() method. That makes it much easier!

  2. tappas Says:

    can’t you just use .parent() inplace of .parents()?

  3. tappas Says:

    oh you already added that. cheers.

Leave a Reply