woggles
woggles

Reputation: 7444

How to highlight table column based on th text using jquery?

Say I have the following table:

<table width=200 border=1>
  <tr>
    <th>Ignore</th>
    <th>Highlight</th>
    <th>Ignore</th>
  </tr>
  <tr>
    <td>yep</td>
    <td>yep</td>
    <td>yep</td>
  </tr>
  <tr>
      <td>yep</td>
      <td>yep</td>
      <td>yep</td>
  </tr>
</table>

and I want to highlight all Highlight columns. How do I do this based on the header text?

I realise it can be achieved by selecting the n'th child, but what to future proof it against likely column order changes.

$('body > table > tbody > tr > td:nth-child(2)').css('background-color', 'pink');

http://jsfiddle.net/8XSLF/

Upvotes: 1

Views: 514

Answers (3)

woggles
woggles

Reputation: 7444

Needed this highlighted in multiple tables: final solution

$("th:contains('Highlight')").each(function() {
    $(this).closest('table').find('td:nth-child(' + ($(this).index() + 1) +')').css('background-color', 'pink');
});

Upvotes: 0

Mohammad
Mohammad

Reputation: 21489

You need to get index of th has Highlight text. So use :contains() selector to selecting it and then use .index() to finding index of it. At the end, select every th and td has index equal to finded index.

Note that the :contains() selector select also element has unwanted text like Highlighted and Text Highlighted. If your table text isn't constant, use .filter() instead.

var i = $("table th:contains('Highlight')").index();
$("table tr th, table tr td").filter(function(){
  return $(this).index() == i;
}).css("background", "pink");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table width=200 border=1>
<tr>
    <th>Ignore</th>
    <th>Highlight</th>
    <th>Ignore</th>
</tr>
<tr>
    <td>yep</td>
    <td>yep</td>
    <td>yep</td>
</tr>
 <tr>
    <td>yep</td>
    <td>yep</td>
    <td>yep</td>
</tr>
</table>

Upvotes: 2

GrafiCode
GrafiCode

Reputation: 3374

Since you specified column name won't change, you can use jQuery.contains:

$( "body > table > tbody > tr > td:contains('Highlight')" ).css('background-color', 'pink');

Upvotes: 0

Related Questions