
Question:
I was wondering how I'd get an alert of a last child by clicking a link.
<h3 id="comment:5" class="myclass">
This is how far I got:
$('#lastcomment').click(function() {
alert('Handler for .click() called.');
});
My aim is to jump to the last comment by clicking the link. An alert would be fine for the first step I guess. So that I can see the last child of the comments.
Any help is much appreciated.
Answer1:Use the <a href="http://api.jquery.com/last-selector/" rel="nofollow">:last
</a> selector or <a href="http://api.jquery.com/last/" rel="nofollow">.last()
</a> method:
$("#lastcomment").click(function () {
var lastComment = $("h3[id^=comment]:last");
alert(lastComment.attr("id"));
}
Answer2:you can use jQuery's :last
selector. but i need to see more HTML to make something work...
So you have a link that you want to go to the last comment on a page? Why not give the comment an id of comment-12 (for example), then just change your anchor to relfect this:
<a class="myclass" href="#comment-12" id="last-comment"> </a>
If you are wanting to do this in javascript, something like:
$('#lastcomment').click(function() {
var numComments = $(".comments").length; // Assuming your comments have a class
window.location = window.location.href + "#" + $(".comments").eq(numComments).attr("id");
});