JQuery, find parent

你。 提交于 2019-12-02 16:34:12
$('#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();
$('#thisid').parents('li')

or if you only want the first one:

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

Simple, use parents()

var parents = $("#thisid").parents('li');
$('#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.

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

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

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

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!