• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

146
Vistas
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>

almost 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

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>

almost 3 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda