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

194
Views
How to get the nearest class of separate div in jquery?

On clicking the button I want to get the closest <input name="something/> value.

I tried $(this).closest(".input").val() but didn't work.

$(document).on("click", ".button", function() {
  div = `<div class="second-div"><input name="something/></div>
         <div class="third-div"></div>`
         
  // get nearest <input name="something/> value
  // get nearest <input class="a-input" /> value
  
  $(".main-div").append(div);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main-div">
  <div class="second-div">
    <input name="something" class="input" />
  </div>
  <div class="third-div">
    <input name="another input" class="a-input" />
  </div>
  <div class="fourth-div">
    <button type="button" class="button">Click Me</button>
  </div>
</div>

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I would traverse up to the containing div first, then back down to the desired control.

$(this).closest(".main-div").find(".input");

EDIT

I just read your comment saying you want to get the last instance of a class.

$(this).closest(".main-div").find(".input").last();

EXAMPLE

$(document).on("click", ".button", function() {
  div = `<div class="second-div"><input name="something" class="input"/></div>
         <div class="third-div"></div>`
         
  $(".input").removeClass("highlight");
  $(this).closest(".main-div").find(".input").last().addClass("highlight");
  // get nearest <input name="something/> value
  // get nearest <input class="a-input" /> value
  
  $(".main-div").append(div);
});
.highlight{
  background:#b00;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main-div">
  <div class="second-div">
    <input name="something" class="input" />
  </div>
  <div class="third-div">
    <input name="another input" class="a-input" />
  </div>
  <div class="fourth-div">
    <button type="button" class="button">Click Me</button>
  </div>
</div>

about 4 years ago · Juan Pablo Isaza 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!