Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
22
rated 0 times [  25] [ 3]  / answers: 1 / hits: 15203  / 11 Years ago, thu, april 25, 2013, 12:00:00

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.


More From » jquery

 Answers
54

I'd do it with .filter() and $.inArray():



var elements = $(table td).filter(function(i) {
return $.inArray(i, indexesToSelect) > -1;
});


Another [more ugly] way is mapping to a selector:



var elements = $($.map(indexesToSelect, function(i) {
return td:eq( + i + );
}).join(,), table);

[#78632] Wednesday, April 24, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
calicinthias

Total Points: 447
Total Questions: 101
Total Answers: 118

Location: Botswana
Member since Sat, Dec 31, 2022
1 Year ago
calicinthias questions
Sun, Jan 2, 22, 00:00, 2 Years ago
Wed, Jan 13, 21, 00:00, 3 Years ago
Mon, Aug 10, 20, 00:00, 4 Years ago
;