Reputation: 3872
I'm stuck with a challenge to change the background color of td elements based on the th class. Below is the html code, which has th class called bots, I've to change the background color of all the td elements below the bots class.
<table border="1" class="CSSTableGenerator" id="myTable">
<tr>
<th>Component</th>
<th>Properties</th>
<th class="bots">J10</th>
<th>J11</th>
<th>J12</th>
<th>J13</th>
</tr>
<tr>
<td>GenerateAlternateTagUrlDroplet</td>
<td>alternateTagConfiguration</td>
<td class="trueValue">/com//jec/website/seo/</td>
<td class="trueValue">/com//jec/website/seo/</td>
<td class="trueValue">/com//jec/website/seo/</td>
<td class="trueValue">/com//jec/website/seo/</td>
</tr>
<tr>
<td>AlternateTagUrlDroplet</td>
<td>tagConfiguration</td>
<td class="trueValue">/jec/website/seo/</td>
<td class="trueValue">/jec/website/seo/</td>
<td class="trueValue">/jec/website/seo/</td>
<td class="trueValue">/jec/website/seo/</td>
</tr>
</table>
Can someone please help me with jquery code to achieve this?
Many Thanks in advance.
Upvotes: 3
Views: 1753
Reputation: 101
Maybe get all th.bots index and use that to color the tds. Assuming you have jQuery:
$('th.bots').each(function(){
$('td:nth-child('+($(this).index() + 1)+')').css('background-color', 'blue');
});
Edit: Excluding other tables on same page http://codepen.io/anon/pen/PzNZrE
$('th.bots').each(function(){
$(this).parents('table').children().find('td:nth-child('+($(this).index() + 1)+')').css('background-color', 'blue');
});
Upvotes: 1
Reputation: 122027
You can use map()
to return array of indexes with .bots
class and then change css of td
with same index.
var bots = $('tr th.bots').map(function() {
return $(this).index();
}).get()
$('tr:not(:first) td').each(function() {
if (bots.indexOf($(this).index()) != -1) $(this).css('background', 'blue')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1" class="CSSTableGenerator" id="myTable">
<tr>
<th>Component</th>
<th>Properties</th>
<th class="bots">J10</th>
<th>J11</th>
<th class="bots">J12</th>
<th>J13</th>
</tr>
<tr>
<td>GenerateAlternateTagUrlDroplet</td>
<td>alternateTagConfiguration</td>
<td class="trueValue">/com//jec/website/seo/</td>
<td class="trueValue">/com//jec/website/seo/</td>
<td class="trueValue">/com//jec/website/seo/</td>
<td class="trueValue">/com//jec/website/seo/</td>
</tr>
<tr>
<td>AlternateTagUrlDroplet</td>
<td>tagConfiguration</td>
<td class="trueValue">/jec/website/seo/</td>
<td class="trueValue">/jec/website/seo/</td>
<td class="trueValue">/jec/website/seo/</td>
<td class="trueValue">/jec/website/seo/</td>
</tr>
</table>
Upvotes: 4
Reputation: 9583
One option would be to do something along the lines of:
var nthChild = $('.bots').index() + 1; // Add 1 since index starts at 0
$("td:nth-child(" + nthChild + ")").css("background", 'yellow');
Upvotes: 2