This article introduces jQuery traversal-methods about closest () and differences between them and parents. If you need a friend, refer to the closest () method to obtain the matching selector.
First Ancestor Element,
Starting from the current elementAlong the DOM tree.
Syntax:
. Closest (selector)
The selector parameter is a string value that contains the selector expression of the matching element.
Given a jQuery object that represents a DOM element set, the. closest () method allows us to retrieve these elements and their ancestor elements in the DOM tree and construct a new jQuery object with matching elements .. The parents () and. closest () methods are similar. They all traverse up the DOM tree. Although the differences between the two are subtle, they are important:
| . Closest () |
. Parents () |
| Starting from the current element |
Starting with the parent Element |
| Traverse up the DOM tree until a match of the applied selector is found. |
Traverse up the DOM tree until the root element of the document adds Each ancestor element to a temporary set. If a selector is applied, the set is filtered Based on the selector. |
| Returns a jQuery object containing zero or one element. |
Returns a jQuery object containing zero, one, or more elements. |
Let's take a look at the following example: demonstrate how to use closest () to delegate events. When clicked by the closest list element or its child element, the yellow background is switched.
The Code is as follows: