I am new to jQuery. I am clicking on a link which sends an ajax request and in the callback I want to change the text of the next p
element.
My html code:
<div>
<img src="/images/{{comment.commenterPicName}}" class="img-circle">
<b>{{comment.commenterFirstName}}</b>
<p>{{comment.commentMessage}}</p>
{% if comment.isLiked %}
<a class="comment-like" id="{{comment.id}}">Unlike</a>
{% else %}
<a class="comment-like" id="{{comment.id}}">Like</a>
{% endif %}
<p>{{comment.likersCount}}</p>
</div>
My jQuery Code:
$(".comment-like").click(function(e) {
var el = $(this);
if ($(this).html() == "Like") {
var parameters = { commentId: $(this).attr('id')};
$.get(
"/likeComment",
parameters,
function(data) {
el.parent().children('p').last().text(data);
}
);
$(this).html('Unlike');
}
else {
var parameters = { commentId: $(this).attr('id')};
$.get(
"/unlikeComment",
parameters,
function(data) {
el.parent().children('p').last().text(data);
}
);
$(this).html('Like');
}
My problem is I can't change the p
element containing likersCount. I tried .next()
.last()
etc. Please help. Thanks in advance.
I have finally found the solution.
Instead of:
el.parent().children('p').last().text(data);
I had to use simply:
el.next('p').text(data);
This will invariably select the next p
element which was precisely the requirement.