This article mainly introduces jQuery's methods for obtaining the parent element and the parent node. It summarizes and analyzes jQuery's common techniques for operating the parent element and the parent node in combination with examples, for more information about how to obtain the parent element and the parent node of jQuery, see the examples in this article. We will share this with you for your reference. The details are as follows:
Jquery has many methods to obtain the parent element. For example, parent (), parents (), and closest () can help you find the parent element or node. Here we will explain it one by one:
For example,
- Jquery obtains the parent node
- Jquery obtains the parent Element
The purpose is to obtain the ul element of class parent1 through the tag a with id item1. There are several methods:
1. parent ([expr])
Obtains a set of elements that contain the unique parent element of all matching elements.
You can use an optional expression to filter data.
The Code is as follows:
$('#item1').parent().parent('.parent1');
2.: parent
Match an element containing child elements or text
The Code is as follows:
$('li:parent');
3. parents ([expr])
Obtains a set of elements (excluding the root element) that contain all the ancestor elements matching the elements ). You can use an optional expression to filter data.
The Code is as follows:
$('#items').parents('.parent1');
4. closest ([expr])
Closest first checks whether the current element matches. If yes, it returns the element itself. If there is no match, the parent element is searched up, and the parent element is located up one layer until the element matching the selector is found. If nothing is found, an empty jQuery object is returned.
The main differences between closest and parents are:
① The former matches the current element and the latter matches the parent element;
② The former searches up one by one until the matching elements are found and then stops. The latter searches up until the root elements are put into a temporary set, filter with the given selector expression;
③ The former returns 0 or 1 element, and the latter may contain 0, 1, or multiple elements.
Closest is very useful for handling event delegation.
$('#items1').closest('.parent1');