The closeest () method does not work as expected

I have an example below, I'm not sure why the first example (using div ) did not get the text if the second (using span ) could achieve this using the same JS code using closest() :

 $('.class-1').closest('div').find('.class-2').text() 

The first fragment (using a div ) cannot get text using closest() :

 console.log( $('.class-1').closest('div').find('.class-2').text() ); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <div class="class-1">Div 1 Content</div> <div class="class-2">Div 2 Content</div> </div> 

The second snippet (using span ), getting the text using closest() :

 console.log( $('.class-1').closest('div').find('.class-2').text() ); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <span class="class-1">Div 1 Content</span> <br/> <span class="class-2">Div 2 Content</span> </div> 

I know about alternatives to parents()/parent()/siblings()/nextAll() that can return class-2 text in this case, but I just want to know what happens to this behavior.

+6
source share
1 answer

Since .closest() checks if the calling element is suitable for the selector, and in your case .class-1 also has a div .

From the docs:

Description: for each element in the set, get the first element that corresponds to the selector by testing the element itself and passing through its ancestors in the DOM tree.

+12
source

Source: https://habr.com/ru/post/1013825/


All Articles