Using jQuery to get multiple items by index

Is there a way to use jQuery to get multiple elements by index - something like . eq () , but where can you go through an array instead of a single index? Something like that:

var arrIndexes = [0, 4, 5]; var stuff = $("#datatable tbody tr").eq(arrIndexes).css('background-color', 'red'); 
+4
source share
2 answers

just use the first argument in the filter (index) and look at it 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 indexOf function if you need older browsers: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf

+8
source

You can use the jquery filter function to apply a custom filter to the collection of objects returned by the selector, you can learn more about the filter here

Live demo

 $("#datatable tbody tr").filter(function(){ if(arrIndexes.indexOf($(this).index()) != -1) return $(this); }).css('background-color', 'red'); 
+3
source

All Articles