jQuery selector first x items of specific class

By Sam Deering

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

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 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++ )
    return elems;



Does anyone know of a better way to achieve this?

Optimised versions Thanks to Vlad, Redky and Daniel. Using slice. [js] var $el = $('div').get().slice(0,10); console.log($el);​

Using :gt :lt

  • Vladimir Kharlampidi

    Yes, there is a more better native way to achieve this using :gt() and :lt() pseudo selectors and their combinations like:

    • jQuery4u

      Hi Vlad, doesn’t seem to work mate, am I doing something wrong?

      • Daniel Trott

        I tested it a little bit and came to the following conclusion:
        With the given div-set from your fiddle and using :gt(5) you first get all divs from index 6, because :gt() and lt() are zero-based indices. From this set you try to get all divs less than the index 10 ( :lt(10) ).
        You can try to set the :lt() index to 1 and you’ll get just one div. So the conclusion here is, that you get first all divs greater than index 5 (div#7 – div#15) and then all divs within this set until index less than 10 (still div#7 – div#15, because there are less then 11 elements).
        On the other hand the slice-operation works well.

        • Vladimir Kharlampidi

          That is right. To output divs from #6 to #10, you need to type $(‘div:gt(4):lt(5)’)

          • jQuery4u

            Yes this would give you els 5-10 $(‘div:gt(3):lt(6)’) –
            My conclusion is with minimum overhead increase by getting all elements initially but slice works best.

  • redky

    We also can use Array.prototype.slice method to achieve this



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.