views:

77

answers:

2
<ul id="comment1">
 <li>reply1</li>
 <li>reply2</li>
 <li>reply3</li>
 <li>reply4</li>
 <li>reply5</li>
 <li>reply6</li>
 <li>reply7</li>
 <li>reply8</li>
</ul>

how to select last 3 or 4 replies with jquery?

+5  A: 

You are looking for slice method:

To get last four items (updated with -4 as suggested by @KennyTM):

$('ul#comment1 li').slice(-4).css('color', '#00ff00');
Sarfraz
Use `.slice(-4)` to select the last 4 replies.
KennyTM
@KennyTM: Updated thanks :)
Sarfraz
@KennyTM: Although I have updated my answer but count for your comments keeps on increasing, interesting :)
Sarfraz
@sAc: It’s probably because `$('ul#comment1 li').slice(1, 4)` is plain wrong. That would get just the second, third and fourth element.
Gumbo
@Gumbo: Yeah right i have removed that quite some time ago though realizing it could be the reason.
Sarfraz
+2  A: 
$('#comment1 li:last-child')
     .prev('li').andSelf()
     .prev('li').andSelf()
     .prev('li').andSelf()
     .prev('li').andSelf()

Should get the last four

Zane Edward Dockery
and then again, there's slice(-4). Which is a much better method IMO
Zane Edward Dockery
Very nice Zane.
steven spielberg