Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

306
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!