Method for jQuery to get element parent node
- 2021-06-29 09:55:17
- OfStack
There are many ways for jquery to get a parent element, such as parent (), parents (), closest (), which can help you find a parent element or node. Here's 11:
Let's start with an example
<ul class="parent1">
<li><a href="#" id="item1">jquery Get Parent Node </a></li>
<li><a href="#">jquery Get parent element </a></li>
</ul>
Our purpose is to retrieve ul element class parent1 from id's note a for item1 in several ways:
1. parent ([expr])
Gets a collection of 1-only parent elements that contain all matching elements.
You can use optional expressions to filter.
The code is as follows
$('#item1').parent().parent('.parent1');
2.: parent
Match elements with child elements or text
The code is as follows
$('li:parent');
3. parents ([expr])
Gets a collection of elements (without the root element) that contain all the ancestor elements of the matching elements.You can filter by an optional expression.
The code is as follows
$('#items').parents('.parent1');
4. closest ([expr])
closest first checks if the current element matches, and returns the element itself if it matches.If they don't match, look up the parent element, layer 1 up, until you find the element that matches the selector.If nothing is found, an empty jQuery object is returned.
The main differences between closest and parents are:
1), the former starts the matching search from the current element, the latter starts the matching search from the parent element;
2) The former searches up one level at a time until a matching element is found and stops, while the latter searches up until the root element, then puts these elements into a temporary set and filters them with the given selector expression;
3), the former returns 0 or 1 element, the latter may contain 0, 1, or more elements.
closest is useful for handling event delegations.
$('#items1').closest('.parent1');