JQuery Nearest - How Does It Work?

JQuery documentation reports

For each element in the set, get the first element that corresponds to the selector by testing the element itself and moving its ancestors in the DOM tree.

The operational word here, in my opinion, is the ancestor . That would mean that if you use

elem.closest(selector) 

and the selector is not the ancestor of the Elev, nothing will be found. However, a little lower in the same document that he reads

Moves the DOM tree until it finds a match for the supplied selector

which I interpret as meaning that he will go all the way to <body> to get his man. Please note: there is no mention of parents or ancestors.

I wrote a quick fiddle which seems to indicate the correctness of the previous statement. However, I thought it was best to post here and see if anyone else could confirm this.

+7
jquery
source share
4 answers

The .closest() implementation works as follows (in pseudocode):

 while (node) { if (node matches selector) { return node; } node := node.parentNode } 

In other words, it goes through only the parent chain.

+7
source share

When he says “Travels the DOM tree” in the second quote, it means “going through his ancestors in the DOM tree” in your first quote. There is no difference between the two statements; one is a paraphrase of the other, which just turns out to be a little less specific.

+4
source share

jQuery closeest () selects the first parent element (by its HTML tag) of the selector or the selector itself (if it matches). For example, if you select the element "p" ($ ("p # someid")), it will begin to search from your element "p", and if there is no match, it moves to it parent. And so on

HTML example:

 <div id='select_me'>Div <p id='id'>paragraph</p> </div> 

$ ('# id'). closeest ('div) // will select the div # select_me as the closest parent div

where as

  <p id='select_me'>Div <p id='select_me_now'>paragraph</p> </p> 

$ ('# select_me_now') nearest (p); // select p # select_me_now

+1
source share

.closest () searches for these elements and their ancestors in the DOM tree and builds a new jQuery object from the corresponding elements.

Example:

 $( "li.item-a" ).closest( "ul" ).css( "background-color", "red" ); 

This will change the color of level-2, as it first occurs when moving through the DOM tree.

+1
source share

All Articles