Selecting First 10 Items of Specific Class Using jQuery


Here’s a very informative technique using jQuery to select the first 10 items of specific class. This tutorial was created by web developer Sam Deering, who is also the man behind jQuery4u.

1. First thing to do is get the first and last elements:

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

2. Get all the elements that will match the specified class:

var allSpans = $('span.class').get();
 or the nth/xth element like so:
 var firstSpan = $('span.class').get(0),
 secondSpan = $('span.class').get(1);
 //etc...

3. If you’ll get the fist 10 elements or even the next batch:

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

4. Below is Deering’s attempt to use jQuery .get() to include range of elements since jQuery .get() doesn’t allow to pass the range, only single index.

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

Incoming search terms for the article:

Related Posts

Calendario: A Responsive jQuery Calendar Plugin

Quickly Convert Hash Into URL Query

Flare: A Responsive Mobile-Optimized Lightbox Plugin

Create A Twitter Timeline Using jQuery And CSS

Leave a Reply









CommentLuv Enabled