I’ve been playing around with this a little. Grabbing a specific number of DOM elements based on a specified class.
First, basics to get the first and last elements like so:
To get all the elements that match a specified class like so:
or the nth/xth element like so:
But how to get say the first 10 elements or elements 10-20?
It would be nice to go something like:
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 <= end; i++ )
{
elems.push(this.get(i));
}
return elems;
};
//testing
console.log($('div').getRange(1,10));
console.log($('div').getRange(10,20));
})(jQuery);
{
//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);
Does anyone know of a better way to achieve this?
No comments:
Post a Comment