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