harshavmb harshavmb - 5 months ago 19
Javascript Question

How to change background color of td elements based on th using jquery

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.

Answer

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>

Comments