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"
CodePudding user response:
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)
})