Reputation: 2259
Is there a way to use jQuery to get multiple elements by index -- something like .eq(), but where you can pass in an array instead of a single index? Something like this:
var arrIndexes = [0, 4, 5];
var stuff = $("#datatable tbody tr").eq(arrIndexes).css('background-color', 'red');
Upvotes: 5
Views: 5825
Reputation: 148150
You can use filter function of jquery to apply custom filter on the collection of objects returned by selector, You can read more about filter here
$("#datatable tbody tr").filter(function(){
if(arrIndexes.indexOf($(this).index()) != -1)
return $(this);
}).css('background-color', 'red');
Upvotes: 3
Reputation: 9031
just use the first argument in filter (index) and look it up with indexOf
var arrIndexes = [0, 4, 5];
$("#datatable tbody tr").filter(function(index) {
return arrIndexes.indexOf(index) > -1;
}).css('background-color', 'red');
demo: http://jsbin.com/ivexut/1/
you may need to add the function indexOf if you are in need of older browsers: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf
Upvotes: 8