Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

417
Views
Closest() in jQuery doesn't work when at the same level

Problem:

I want (after clicking on a button - this part is OK) to select the closest element with a class .my-textarea, but the using of prev() is not always possible, because the code is dynamic. Could you help?

Details:

I have this HTML code:

<div class="row">
    <div class="label">Description:</div>
    <textarea class="my-textarea" name="my-textarea" rows="8" cols="40"></textarea>
    <button type="button" class="my-submit" name="my-submit">Save</button>
</div>

And my JS code (in on button with class "my-submit" click event) is:

var text = $(this).closest('.my-textarea').val();

But it's not working. I am getting undefined.

If I tried:-

var text = $(this).prev().val();

I will get the text of the text-area, but as I've mentioned, my code is dynamic and the order and number of elements will change. So, prev() is out of option.

Any idea how to make closest() work?

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

I always select parent and than search for child with class. That way your element can be placed virtually anywhere in parent.

$(this).parent().find('.my-textarea').val();
about 4 years ago · Santiago Trujillo Report

0

Need to Use siblings() instead of closest():-

$('.my-submit').click(function(e){
  e.preventDefault();
  var text = $(this).siblings('textarea').val();
  console.log(text);
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
    <div class="label">Description:</div>
    <textarea class="my-textarea" name="my-textarea" rows="8" cols="40"></textarea>
    <button type="button" class="my-submit" name="my-submit">Save</button>
</div>

about 4 years ago · Santiago Trujillo Report

0

You need to refer it using class

closest will traverse up the DOM tree to look for the element, while in this case textarea is sibling of the button.

 $('.my-submit').click(function(){
    var text = $(this).siblings('.my-textarea').val();
    alert(text)
    })

DEMO

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!