Jquery Closest - How does it work

103 views Asked by At

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`

1

There are 1 answers

0
j08691 On

Use either .prev() or .parents():

var value = $(".parentDiv").parents("div").children(".firstChild").text();
console.log(value);

var value = $(".parentDiv").prev(".firstChild").text();
console.log(value);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
  <div class="firstChild">12345</div>
  <div class="parentDiv">
    <div class="firstChild">1234</div>
    <div class="secondChild">Hello</div>
    <div class="thridChild">Bye</div>
  </div>
</div>

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.