Using jquery to get a parent element or parent node is simpler, and jquery provides a rich way for us to use jquery to get a parent or parent node
jquery Gets the parent element method is more, such as parent (), parents (), closest () These can help you to find the parent element or node, let us one by one to explain:
Let me give you 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 goal is to get the UL element of class Parent1 by using note A with ID item1, in the following ways:
1. Parent ([expr])
Gets a collection of elements that contain the unique parent element for all matching elements.
You can use an optional expression to filter.
The code is as follows
$ (' #item1 '). Parent (). Parent ('. Parent1 ');
2,:p arent
Match elements that contain child elements or text
The code is as follows
$ (' li:parent ');
3. Parents ([expr])
Gets a collection of elements containing the ancestor elements of all matching elements (without the root element). You can filter by an optional expression.
The code is as follows
$ (' #items '). Parents ('. Parent1 ');
4. Closest ([expr])
Closest first checks whether the current element matches, and if so, returns the element itself directly. If it does not match, look up the parent element, one layer at a level, until the element that matches the selector is found. If nothing is found, an empty jquery object is returned.
The main differences between the closest and parents are: 1, the former from the current element to match the search, the latter from the parent element to match the search, 2, the former step up the search, until the matching element is found to stop, the latter has been looking up until the root element, and then put these elements into a temporary collection, Filter by a given selector expression, 3, which returns 0 or 1 elements, which may contain 0, 1, or more elements.
Closest is useful for handling event delegation.
$ (' #items1 '). Closest ('. Parent1 ');
Use jquery to get a parent or parent node