Instance
This example demonstrates how to complete an event delegate through closest (). When clicked by the closest list element or its child descendant elements, the yellow background is toggled:
$ (document). Bind ("click", Function (e) { $ (e.target) .closest("li")
. Toggleclass ("Hilight"); });
Definition and usage
The closest () method obtains the first ancestor element of a matching selector, starting at the current element along the DOM tree.
Grammar
. Closest (selector)
Parameters |
Description |
Selector |
A string value that contains the selector expression for the matching element. |
Detailed description
Given a JQuery object that represents a collection of DOM elements, the. Closest () method allows us to retrieve these elements in the DOM tree and their ancestor elements, and constructs a new JQuery object with matching elements: similar to the parents () and. Closest () methods, they all follow the The DOM tree is traversed upward. The difference between the two is very important, albeit subtle:
. Closest () |
. Parents () |
Start with the current element |
Start with the parent element |
Walk up the DOM tree until you find a match for the selector you have applied. |
Iterates up the DOM tree until the root element of the document, adding each ancestor element to a temporary collection, and if the selector is applied, the collection is filtered based on that selector. |
Returns a JQuery object that contains 0 or one element |
Returns a JQuery object that contains 0, one, or more elements |
Take a look at the following HTML snippet:
<ul id= "One" class= "Level-1" > <li class= "item-i" >I</li> <li id= "II" class= "Item-ii" >ii <ul class= "Level-2" > <li class= "item-a" >A</li> <li class= "Item-b" >b <ul class= "level-3" > <li class= "item-1" >1</li> <li class= "Item-2" >2</li > <li class= "item-3" >3</li> </ul> </li> <li class= "Item-c" > c</li> </ul> </li> <li class= "ITEM-III" >III</li></ul>
Example 1
Let's say we perform a search for the <ul> element starting with Project A:
$ (' li.item-a '). Closest (' ul '). CSS (' background-color ', ' red ');
This changes the color of the Level-2 <ul> because it is the first to be encountered when walking up the DOM tree.
Example 2
Let's say we're searching for <li> elements:
$ (' li.item-a '). Closest (' Li '). css (' background-color ', ' red ');
Closest () a function that is useful in comments