I have searched and referred to the earlier questions asked but may be I am too stupid to understand the issue :) .
I was referring to the jQuery implementation for closest and after reading it I tried to implement it on a very simple dummy example. But somehow I am not able to get the values. Below is the code I am using
<div>
<div class="firstChild">1234</div>
<div class="parentDiv">
<div class="firstChild">1234</div>
<div class="secondChild">Hello</div>
<div class="thridChild">Bye</div>
</div>
</div>
and the jQuery code I am using it
$(document).ready(function(){
var value = $( ".parentDiv" ).closest( ".firstChild" ).text();
alert(value);
});
but all I am getting as the value is blank. when I tried using
var value = $( ".parentDiv" ).closest( "div" ).text();
I get the value from all the three child div's ie (1234 Hello Bye) as alert
How do I use closest selector to get the value of firstChild`
Use either
.prev()
or .parents()
:The issue with using
.closest()
in your example is that unlike.parents()
,.closest()
will test itself, and then go up the DOM. So.closest('div')
will select the parentDiv div which isn't what you want. You could always use .closest() and specify a div with no class, but there's no point when two other selectors are more appropriate.