5

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');
1
  • 1
    How about just using a for loop? You cannot expect jquery to have every utility method known to man. Commented Aug 7, 2012 at 17:24

2 Answers 2

8

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

Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly what I was looking for... I plugged it into my code and it worked like a charm. Thank you!
3

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');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.