jQuery Closest - how does it work?

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


jQuery closest() selects first parent element (by it HTML tag) of the selector, or selector itself (if it matches). It's like if you are selecting 'p' element ($('p#someid')), it starts searching from your 'p' element and if there is no match, it moves to it's parent. And so on

Example HTML:

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

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

where as

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

$('#select_me_now').closest("p"); // will select p#select_me_now itself


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.


When it says "Travels up the DOM tree" in the second quote, it means "traversing up through its ancestors in the DOM tree" in your first quote. There's no difference between both of the statements quoted; one is a paraphrase of the other that just happens to be slightly less specific.

Tags:

Jquery