Select last 5 elements with jQuery

JqueryCss Selectors

Jquery Problem Overview


Is it possible to select the last 5 child divs of an element?

Jquery Solutions


Solution 1 - Jquery

Yes, you can get the div elements, and then use the slice method to get the last five:

var e = $('#someelement > div').slice(-5);

Solution 2 - Jquery

Sure, you could use the .length property of a selector to get the count, and then use the :gt(n) selector to get the last 5.

var o = $("div.container > div:gt("+($("div.container > div").length-5)+")");

Solution 3 - Jquery

As of jQuery 1.8, you can use a negative value in the :gt() pseudo selector.

Reference: https://api.jquery.com/gt-selector.

e.g.

var e = $('#someelement > div:gt(-6)');

JSFiddle: https://jsfiddle.net/TrueBlueAussie/g4drety2/3/

Notes:

  • The value needs to be n+1
  • .slice(-5) is faster as :gt cannot use browser performance boosting.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAdamView Question on Stackoverflow
Solution 1 - JqueryGuffaView Answer on Stackoverflow
Solution 2 - JquerySampsonView Answer on Stackoverflow
Solution 3 - JqueryGone CodingView Answer on Stackoverflow