closest() method not working as expected

余生长醉 提交于 2019-12-06 02:53:53

问题


I've a sample example below, I'm not sure why the first example (using div's) didn't get the text when the second one (using span's) could achieve that with the same JS code using closest():

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

First snippet (using div's) cant get 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>
  <div class="class-1">Div 1 Content</div>
  <div class="class-2">Div 2 Content</div>
</div>

Second snippet (using span's) 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 the alternatives parents()/parent()/siblings()/nextAll() that can return the class-2 text in this case, but I want just to know what occur this behaviour.


回答1:


Because .closest() checks if the calling element fits the selector as well, and in your case .class-1 is also a div.

From the docs:

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



来源:https://stackoverflow.com/questions/41508008/closest-method-not-working-as-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!