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');
Definition and Usage. The element selector can also be used to select multiple elements. Note: Seperate each element with a comma.
The index() is an inbuilt method in jQuery which is used to return the index of the a specified elements with respect to selector. Parameter: It accepts an optional parameter “element” which is used to get the position of the element. Return value: It returns an integer denoting the index of the specified element.
jQuery eq() Method The eq() method returns an element with a specific index number of the selected elements. The index numbers start at 0, so the first element will have the index number 0 (not 1).
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
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
Live Demo
$("#datatable tbody tr").filter(function(){
if(arrIndexes.indexOf($(this).index()) != -1)
return $(this);
}).css('background-color', 'red');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With