Home > Article > Web Front-end > How to get parent and elements above parent with jQuery
jquery is widely used in front-end development. You can use jQuery to obtain child elements, parent elements, sibling elements, etc. This article will tell you how to use jQuery to obtain parent elements and elements above the parent element. If necessary Friends can take a look, I hope it is useful to you.
parent(), parents(), closest()These methods can all be used to find parent elements or nodes
First there is an example:
<ul class="parent1"> <li><a href="#" id="item1">jquery获取父节点</a></li> <li><a href="#">jquery获取父元素</a></li> </ul>
Our purpose is to get the ul element with class parent1 through note a with id item1. There are several methods:
1, parent([expr])
Get an element set containing the unique parent element of all matching elements.
For example:
$('#item1').parent().parent('.parent1');
2, :parent
Matches elements containing child elements or text
$('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.
$('#items').parents('.parent1');
4. closest([expr])
closest will first check whether the current element matches, and if it matches, it will directly return the element 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');
The above is the detailed content of How to get parent and elements above parent with jQuery. For more information, please follow other related articles on the PHP Chinese website!