Reputation:
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>
Upvotes: 0
Views: 80
Reputation: 2859
You can try this:
$("tr[class*='row'] td span").addClass('foo')
Upvotes: 0
Reputation: 14746
var array = [1,2,4]; // etc...
$(array.map(function(i) {return ".row-" + i;}).join(',')).addClass('bar');
In es6:
const array = [1,2,4]; // etc...
$(array.map(i => `.row-${i}`).join(',')).addClass('bar');
edit You can also use directly reduce, i.e. (es6)
$(`.row-${array.reduce((a, b) => `${a},.row-${b}`)}`).addClass('bar');
Upvotes: 3
Reputation: 68393
try this
var ids = [1,2,4];
$( "tr[class^='row']" ).each( function(){
var index = parseInt( $(this)[0].className.split("-")[1], 10 );
if( ids.indexOf( index ) != -1 )
{
$(this).addClass("bar");
}
});
.bar
{
color :red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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>
Upvotes: 1