Faili
Faili

Reputation: 1000

Selecting the last child

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.

Upvotes: 1

Views: 184

Answers (3)

Alex
Alex

Reputation: 7374

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

Upvotes: 0

Andy E
Andy E

Reputation: 344575

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

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

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

Upvotes: 3

Stefanvds
Stefanvds

Reputation: 5916

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

Upvotes: 0

Related Questions