I’m stucking with jQuery where I need to use closest to get the .text() of the wanted element.
Here is the HTML:
<div class="endorse-set">
<div class="endorse">
<span class="keyword" id="keyword-1">web developer</span>
<textarea class="comment" id="comment-1"></textarea>
<input type="button" class="endorse-button" id="endorse-button-1" value="Endorse">
</div>
<div class="endorse">
<span class="keyword" id="keyword-2">web designer</span>
<textarea class="comment" id="comment-2"></textarea>
<input type="button" class="endorse-button" id="endorse-button-2" value="Endorse">
</div>
<div class="endorse">
<span class="keyword" id="keyword-3">Entrepreneur</span>
<textarea class="comment" id="comment-3"></textarea>
<input type="button" class="endorse-button" id="endorse-button-3" value="Endorse">
</div>
</div>
I need to get the .text() i.e. web designer or web developer or entrepreneur and the .comment value, when the user clicks .endorse-button
I tried like this and failed:
$(".endorse-button").click(function(){
var keyword = $(this).closest('span.keyword').text();
var comment = $(this).closest('textarea.comment').val();
alert(keyword);
alert(comment);
});
I’m getting nothing. Could you help me?
P.S. I’m new to jQuery!
Thanks!
The
closestmethod looks at ancestor elements (e.g. the parentdiv.endorse, and the parent of that etc). The elements in question are siblings, so you can use thesiblingsmethod: