Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Closest - how does it work?

Tags:

jquery

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.

like image 668
DroidOS Avatar asked Oct 19 '13 06:10

DroidOS


People also ask

How does closest work in JavaScript?

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.

What is $() in jQuery?

$() = 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.

What is the difference between parent () and parents () methods in jQuery?

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.

What is .next in jQuery?

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.


2 Answers

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.

like image 198
Ja͢ck Avatar answered Sep 20 '22 11:09

Ja͢ck


.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.

like image 22
tilak Avatar answered Sep 23 '22 11:09

tilak