Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery, find parent

Tags:

jquery

parent

People also ask

How do I find a specific parent in jQuery?

The parents() is an inbuilt method in jQuery which is used to find all the parent elements related to the selected element. This parents() method in jQuery traverse all the levels up the selected element and return that all elements.

What is jQuery parent?

The parents() method returns all ancestor elements of the selected element. An ancestor is a parent, grandparent, great-grandparent, and so on. The DOM tree: This method traverse upwards from the parent element along ancestors of DOM elements, all the way up to the document's root element (<html>).

How do I find a Div parent?

To get the parent node of an HTML element, you can use the parentNode property. This property returns the parent node of the specified element as a Node object.


$('#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();
  • http://api.jquery.com/closest/
  • http://api.jquery.com/parents/

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

or if you only want the first one:

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

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

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


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.


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