Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

424
Vistas
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?

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

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();
over 4 years ago · Santiago Trujillo Denunciar

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>

over 4 years ago · Santiago Trujillo Denunciar

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

over 4 years ago · Santiago Trujillo 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 Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda