49
<ul><li><div><div><span id="thisid"></span></div></div></li></ul>

$('#thisid').parent('li');

that obviously doesn't work, but how do I grab the li element? I don't want to use:

$('#this').parent().parent().parent();

I don't want to use it, because it can happen that there is just one div element, instead of two. In this case I would grab the ul element instead of the li element.

7 Answers 7

99
$('#thisid').parents('li');
//                 ^ plural!

Note that if you only want the first <li> element in the ancestry, you should use closest():

$('#thisid').closest('li');

// `closest()` is equivalent to (but performs better than)
$('#thisid').parents('li').eq(0);
$('#thisid').parents('li').first();
Sign up to request clarification or add additional context in comments.

3 Comments

All four examples are great solutions.
Just wanted to make it clear that singular "parent()" is a valid function call; it just doesn't do what the question-asker was needing.
This solution works like a charm, just want to point a caveat: .closest() also checks the actual element from which it is called: If the element has the same selector as the requested parent, it won't work. You need to use .parents() in such case. For me, .parents('someSelector').eq(0) worked out just fine.
7
$('#thisid').parents('li')

or if you only want the first one:

$('#thisid').closest('li')

Comments

3
$('li').has('#thisid')

http://api.jquery.com/has/

1 Comment

interesting alternative, although potentially a lot slower
2

Simple, use parents()

var parents = $("#thisid").parents('li');

Comments

2
$('#thisid').parents( 'li:eq(0)' ); 

Should do it. This will give you the first (:eq(0)) parent that matches being the tag you're searching for.

Comments

1

I prefer the 'closest' than 'parents'.

Parents travel up the DOM tree to the document's root element, adding each ancestor element to a temporary collection; it then filters that collection based on a selector if one is supplied.

where

Closest Travel up the DOM tree until it finds a match for the supplied selector.

Most important what they give in result:

Praents: Returned jQuery object contains zero or more elements for each element in the original set, in reverse document order.

Closest: Returned jQuery object contains zero or one element for each element in the original set, in document order

$('#thisid').closest('li');

Follow this Link

Comments

0

You may actually want to use $("#thisid").closest('li'). This traverses up the DOM tree from the selected node and returns the first matching ancestor whereas the .parents() travels from the parent node and returns all ancestor nodes matching that filter. See here for more information.

Comments