donpedroper donpedroper - 5 months ago 9
Javascript Question

Find DOM elements from values in array

I have a potential big list of id's, in this example: "1, 2, 4"

How can I loop through all rows inside a table and add a class to the element inside where the row is being matched with the class from the array? (using jQuery/javascript)

So this table:

<table>
<tr class="row-1">
<td><span class="foo">1</span></td>
</tr>
<tr class="row-2">
<td><span class="foo">2</span></td>
</tr>
<tr class="row-3">
<td><span class="foo">3</span></td>
</tr>
<tr class="row-4">
<td><span class="foo">4</span></td>
</tr>
<tr class="row-5">
<td><span class="foo">5</span></td>
</tr>
</table>


Looks like this afterwards:

<table>
<tr class="row-1">
<td><span class="foo bar">1</span></td>
</tr>
<tr class="row-2">
<td><span class="foo bar">2</span></td>
</tr>
<tr class="row-3">
<td><span class="foo">3</span></td>
</tr>
<tr class="row-4">
<td><span class="foo bar">4</span></td>
</tr>
<tr class="row-5">
<td><span class="foo">5</span></td>
</tr>
</table>

Answer
var array = [1,2,4]; // etc...
$(array.map(function(i) {return ".row-" + i;}).join(',')).addClass('bar');

Fiddle

In es6:

const array = [1,2,4]; // etc...
$(array.map(i => `.row-${i}`).join(',')).addClass('bar');

Fiddle(es6)