Home >Web Front-end >JS Tutorial >Can jquery get the parent element?
jquery can get the parent element. There are many ways to get the parent element in jquery, such as parent(), parents(), closest(), etc., which can get the parent element or node; parent() returns the direct parent element of the selected element, and closest() returns the parent element of the selected element. The first ancestor element.
Related recommendations: "jq视频"
jquery has many methods to get the parent element, such as parent(), parents(), closest() can help you find parent elements or nodes. Let’s explain them one by one:
Let’s give an example first,
<ul class="parent1"> <li><a href="#" id="item1">jquery获取父节点</a></li> <li><a href="#">jquery获取父元素</a></li> </ul>
Our purpose is to use the id To get the ul element with class parent1 for note a of item1, there are several methods:
1, parent([expr])
Get an element set containing the unique parent element of all matching elements.
You can use optional expressions to filter.
The code is as follows
$('#item1').parent().parent('.parent1');
2, :parent
Matches elements containing child elements or text
The code is as follows
$('li:parent');
3, parents([expr])
Get an element set containing the ancestor elements of all matching elements (excluding the root element). Can be filtered by an optional expression.
The code is as follows
$('#items').parents('.parent1');
4. closest([expr])
closest will first check whether the current element matches, and if it matches, it will return the element directly itself. If there is no match, search upwards for the parent element, layer by layer, until an element matching the selector is found. If nothing is found, an empty jQuery object is returned.
The main difference between closest and parents is: 1. The former starts matching and searching from the current element, while the latter starts matching and searching from the parent element; 2. The former searches upwards step by step until it finds a matching element and then stops. , the latter searches upwards until the root element, then puts these elements into a temporary collection, and then uses the given selector expression to filter; 3. The former returns 0 or 1 elements, and the latter may contain 0, 1 or more elements.
closest is useful for handling event delegation.
$('#items1').closest('.parent1');
For more programming-related knowledge, please visit: Programming Learning Course! !
The above is the detailed content of Can jquery get the parent element?. For more information, please follow other related articles on the PHP Chinese website!