I have the following divs:
<div class="vote">
<input type="hidden" name="reply-id" value="83743">
<a class="vote-up-0" title="Vote Up This Comment">up</a>
<a class="vote-down-0" title="Vote Down This Comment">down</a>
</div>
<div class="vote">
<input type="hidden" name="reply-id" class="reply-id" value="83745">
<a class="vote-up-0" title="Vote Up This Comment">up</a>
<a class="vote-down-0" title="Vote Down This Comment">down</a>
</div>
(Yes, it's a blatent(ish) copy of SO code, I'm trying to see how they do it). So when a user clicks either vote up or vote down, it should find the hidden id.
This doesn't seem to work:
$('a.vote-up-0').click(function() {
var id = $(this).closest('.reply-id').val();
closest
works by going up the DOM tree to find the first element that matches a selector. It only matches ancestor elements. At no point does it look at sibling elements.
You want to use siblings
:
$(this).siblings('.reply-id').val();
If you want to generalise it slightly, to work with any input
-element names, without necessarily knowing the names of the parent elements, you could use:
var idOfHiddenInput = $(this).parent().find('input:hidden:first').attr('id');
References:
parent()
find()
:hidden
selectorIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With