jQuery .closest()
Learn all about the jQuery function .closest().
Given a jQuery object that represents a set of DOM elements, the .closest()
method searches through these elements and their ancestors in the DOM tree and constructs a new jQuery object from the matching elements. The .parents()
and .closest()
methods are similar in that they both traverse up the DOM tree. The differences between the two, though subtle, are significant:
.closest() |
.parents() |
---|---|
Begins with the current element | Begins with the parent element |
Travels up the DOM tree until it finds a match for the supplied selector | Travels up the DOM tree to the document’s root element, adding each ancestor element to a temporary collection; it then filters that collection based on a selector if one is supplied |
The returned jQuery object contains zero or one element for each element in the original set, in document order | The returned jQuery object contains zero or more elements for each element in the original set, in reverse document order |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
|
Suppose we perform a search for <ul>
elements starting at item A:
1
2
3
|
|
This will change the color of the level-2 <ul>
, since it is the first encountered when traveling up the DOM tree.
Suppose we search for an <li>
element instead:
1
2
3
|
|
This will change the color of list item A. The .closest()
method begins its search with the element itself before progressing up the DOM tree, and stops when item A matches the selector.
We can pass in a DOM element as the context within which to search for the closest element.
1
2
3
4
5
6
7
|
|
This will change the color of the level-2 <ul>
, because it is both the first <ul>
ancestor of list item A and a descendant of list item II. It will not change the color of the level-1 <ul>
, however, because it is not a descendant of list item II.