Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use jQuery to select multiple elements with .eq()

I want to select a subset of tds from a table.

I know before hand what the indexes are, but they are effectively random (not odd or even indexes, etc).

For instance say I want to select the 0th, 5th and 9th td.

indexesToSelect = [0, 5, 9];

// 1) this selects the one by one
$('table td').eq(0)
$('table td').eq(5)
$('table td').eq(9)


// 2)this selects them as a group (with underscore / lodash)
var $myIndexes = $();

_.forEach(indexesToSelect, function (idx) {
    $myIndexes = $myIndexes.add($('table td').eq(idx));
});

So (2) works and I am using that, but I wonder if there is a more natural way using jQuery.

Something like passing .eq() an array of indexes? (that doesn't work)

// does not work
$('table td').eq([0, 5, 9])

If not I will write a small plugin for something like .eqMulti(array).

Note: there is no class that these tds share exclusively, so selecting based on class won't work.

like image 436
Sean Avatar asked Apr 25 '13 11:04

Sean


People also ask

Can you select multiple elements in jQuery?

In jQuery, you can select multiple elements by separate it with a comma “,” symbol.

What is the use of EQ in jQuery?

Definition and Usage The :eq() selector selects an element with a specific index number. The index numbers start at 0, so the first element will have the index number 0 (not 1). This is mostly used together with another selector to select a specifically indexed element in a group (like in the example above).

How do you select multiple elements in Javascript?

Use the querySelectorAll() method to select elements by multiple ids, e.g. document. querySelectorAll('#box1, #box2, #box3') . The method takes a string containing one or more selectors as a parameter and returns a collection of the matching elements.

How do you select multiple elements?

Selecting multiple elements Alternatively, hold down the Ctrl / Shift key on your keyboard (Cmd key for Mac) and click the elements to select them. Tip: You can select all elements at once by pressing Ctrl+A on your keyboard.


1 Answers

I wrapped VisioN's filter method into a jQuery plugin:

$.fn.eqAnyOf = function (arrayOfIndexes) {
    return this.filter(function(i) {
        return $.inArray(i, arrayOfIndexes) > -1;
    });
};

So now usage is nice and clean:

var $tds = $('table td').eqAnyOf([1, 5, 9]);
like image 51
Sean Avatar answered Sep 28 '22 05:09

Sean