jQuery selector first x items of specific class

Share this article

I’ve been playing around with this a little. Grabbing a specific number of DOM elements based on a specified class.

Update 27/11/12: Optimised versions below.

First, basics to get the first and last elements like so:

var firstSpan = $('span.class:first'),
    lastSpan = $('span.class:last');

To get all the elements that match a specified class like so:

var allSpans = $('span.class').get();

or the nth/xth element like so:

var firstSpan = $('span.class').get(0),
    secondSpan = $('span.class').get(1);
    //etc...

But how to get say the first 10 elements or elements 10-20?

It would be nice to go something like:

var mySpans = $('span.class').get(0,10);

Unfortunately, the .get() function doesn’t allow for a range to be passed, but just a single index. So here is an attempt to use the jQuery .get() function to include a range of elements.

(function($)
{
  //function that gets a range of dom elements against a jQuery selector
  //returns an array of dom elements
  $.fn.getRange = function(start,end)
  {
    var elems = [];
    for ( var i = start; i Optimised versions
Thanks to Vlad, Redky and Daniel.

Using slice. 
[js]
var $el = $('div').get().slice(0,10);
console.log($el);

Using :gt :lt

console.log($('div:gt(3):lt(6)'));
Sam DeeringSam Deering
View Author

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

jQuery
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week