The jQuery documentation states
For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
The operational word here, to my eyes, is ancestor. Which would imply that if one uses
elem.closest(selector)
and selector is not an ancestor of elem nothing will be found. However, a little lower down in the same document it reads
Travels up the DOM tree until it finds a match for the supplied selector
which I interpret as meaning that it will go all the way up to the <body> tag to get its man. Note, no mention of parent or ancestor here.
I wrote up a quick fiddle which appears to suggest that it is the former statement that is correct. However, I thought it best to post here and see if anyone else can confirm this.
The closest() method searches up the DOM tree for elements which matches a specified CSS selector. The closest() method starts at the element itself, then the anchestors (parent, grandparent, ...) until a match is found. The closest() method returns null() if no match is found.
$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.
parent() method returns the direct parent element of the selected one. This method only traverse a single level up the DOM tree. parents() method allows us to search through the ancestors of these elements in the DOM tree.
Definition and Usage. The next() method returns the next sibling element of the selected element. Sibling elements are elements that share the same parent. The DOM tree: This method traverse forward along the next sibling of DOM elements.
The implementation of .closest()
works like this (in pseudo code):
while (node) {
if (node matches selector) {
return node;
}
node := node.parentNode
}
In other words, it traverses up by following the parent chain only.
.closest() method searches through these elements and their ancestors in the DOM tree and constructs a new jQuery object from the matching elements.
Ex:
$( "li.item-a" ).closest( "ul" ).css( "background-color", "red" );
This will change the color of the level-2 , since it is the first encountered when traveling up the DOM tree.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With