JQuery, find parent

user317005 picture user317005 · Jan 17, 2011 · Viewed 69.5k times · Source
<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.

Answer

Andy E picture Andy E · Jan 17, 2011
$('#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();