Skip to content Skip to sidebar Skip to footer

Selecting The Last Child

I was wondering how I'd get an alert of a last child by clicking a link.

This is how far I got: $('#lastcomment').click(function() {

Solution 1:

Use the :last selector or .last() method:

$("#lastcomment").click(function () { 
    var lastComment = $("h3[id^=comment]:last");

    alert(lastComment.attr("id"));
}

Solution 2:

you can use jQuery's :last selector. but i need to see more HTML to make something work...


Solution 3:

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");
});

Post a Comment for "Selecting The Last Child"