JQuery, find parent

2019-03-08 13:10发布

<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.

标签: jquery parent
7条回答
疯言疯语
2楼-- · 2019-03-08 13:40
$('#thisid').parents('li')

or if you only want the first one:

$('#thisid').closest('li')
查看更多
Deceive 欺骗
3楼-- · 2019-03-08 13:41
$('#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();
查看更多
欢心
4楼-- · 2019-03-08 13:41
$('#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.

查看更多
兄弟一词,经得起流年.
5楼-- · 2019-03-08 13:47

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

查看更多
神经病院院长
6楼-- · 2019-03-08 13:50
$('li').has('#thisid')

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

查看更多
爷、活的狠高调
7楼-- · 2019-03-08 14:01

Simple, use parents()

var parents = $("#thisid").parents('li');
查看更多
登录 后发表回答