This article mainly introduces Jquery's method to search for parent elements. examples show how to use parents, cloest, parent, parentsUtil, and offsetParent, for more information about how to search for a parent element in Jquery, see the following example. Share it with you for your reference. The specific analysis is as follows:
1. parents () method
Format:
The Code is as follows:
Parents ([selector])
Used to obtain the ancestor elements of each element in the currently matched element set. You can also use a selector to filter the elements as needed.
For example:
The Code is as follows:
$ ("P" ).parents().css ("border", "1px solid blue );
2. cloest Method
Format:
The Code is as follows:
Closest (selector [, context])
Starting from the element itself, this method matches the parent element step by step and returns the first matched element.
For example:
The Code is as follows:
$ ("A"). closest ("p" ).css ("border", "1px solid blue ");
The main differences between cloest () and parents () methods are as follows:
① The former searches for matching from the current element, and the latter searches for matching from 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.
3. parent () method
Format:
The Code is as follows:
Parent ([selector])
Used to obtain the parent element of each element in the currently matched element set. You can also use a selector to filter the elements as needed.
For example:
The Code is as follows:
$ ("P" pai.parent().css ("border", "1px solid blue ");
4. parentsUtil () method
Format:
The Code is as follows:
ParentsUtil ([selector])
Used to obtain the ancestor element of each element in the currently matched element set until the element matched by the given selector (but not including this element)
For example:
The Code is as follows:
$ ("Li # li2"). parentsUtil ("# ulstmli2" ).css ("background", "# FCF ");
5. offsetParent () method
Used to search for the located parent element of the First Matching Element, which is only valid for visible elements. The syntax format is as follows:
The Code is as follows:
OffsetParent ()
This method is used to locate the first matched element and return the jQuery object encapsulated by this element.
Example:
The Code is as follows:
Search for the ancestor and parent elements of a specified element from the document