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

307
Visualizações
Why does jQuery .text() not return the value inside the div?

I am missing something trivial here, but I don't get it. Why doesn't it alert Test Value?

$('.comment-upvote-wrapper').on('click', function() {
    // Get the comments pk
    var comment_pk = $(this).closest('#comment-pk').text()
    alert(comment_pk)
})
.comment-upvote-wrapper {
  width: max-content;
  background-color: yellow;
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div hidden id="comment-pk">Test Value</div>
<div class="comment-box">
  <div class="comment-options">
    <div class="comment-upvote-wrapper comment-options-box">Return "Text Value"

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The problem is because #comment-pk is not an ancestor element of .comment-upvote-wrapper, it's a sibling of .comment-box. Therefore you need to use closest() to get the .common-box, then prev():

$('.comment-upvote-wrapper').on('click', function() {
  var comment_pk = $(this).closest('.comment-box').prev('#comment-pk').text();
  console.log(comment_pk)
})
.comment-upvote-wrapper {
  width: max-content;
  background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div hidden id="comment-pk">Test Value</div>
<div class="comment-box">
  <div class="comment-options">
    <div class="comment-upvote-wrapper comment-options-box">Return "Text Value"</div>
  </div>
</div>

However the fact that the element has an id attribute means there should only ever be one of them in the DOM. As such using DOM traversal to find it is redundant; you can just select it directly by its id:

$('.comment-upvote-wrapper').on('click', function() {
  var comment_pk = $('#comment-pk').text();
  console.log(comment_pk)
})
about 4 years ago · Juan Pablo Isaza 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