jQuery select first x items of specific class

By Sam Deering

I have written a little jQuery function call .getRange() which returns a specific number of DOM elements against a jQuery selector (ie elements based on a specified class or id). It uses the jQuery.get() function and is basically an extension of that but allows for a range of elements to be returned.

Firstly, you should know 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 element like so:

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

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 my attempt to use the jQuery .get() function to include a range of elements.

//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 < = end; i++ ) { elems.push(this.get(i)); } return elems; }; //testing console.log($('div').getRange(1,10)); console.log($('div').getRange(10,20)); })(jQuery); [/js] Output: get-range

It works this way, but i’m thinking it’s not an optimal solution so does anyone know of a better way to achieve this?

  • Karl Swedberg

    You could use jQuery’s .slice() method. Then, if you want the DOM element array instead of the jQuery object, just call .get() after that.

  • Samuel

    Perhaps, you can do it using javascript core function splice?
    I have tried :
    (or perhaps : $('div').toArray().getRange(1,10)) and it seems to return a correct result…

  • jquery4u

    Thanks guys, I totally had a blonde moment there!



Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in JavaScript, once a week, for free.