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

308
Vistas
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 Respuestas
Responde la pregunta

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