Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

419
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda