Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery to get multiple elements by index

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');
like image 909
Mass Dot Net Avatar asked Aug 07 '12 17:08

Mass Dot Net


People also ask

Can you select multiple elements in jQuery?

Definition and Usage. The element selector can also be used to select multiple elements. Note: Seperate each element with a comma.

How to get element index jQuery?

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.

What is eq in jQuery?

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).


2 Answers

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

like image 91
voigtan Avatar answered Sep 28 '22 18:09

voigtan


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');
like image 29
Adil Avatar answered Sep 28 '22 18:09

Adil