0

I am trying to use jQuery to change the background color of the body whenever a specific text (the letter “Y”) is found in a specific column.

The following only changes the background color of the table cell that it finds “Y” in.

$(document).ready(function () {
        $("TD:nth-of-type(7):contains('Y')").css("background-color", "yellow");
});

I’ve tried it with body:background-color but it doesn’t work.

Thanks!

1 Answers1

1

Your script will only color your cell:

$(document).ready(function () {
    $("TD:nth-of-type(7):contains('Y')").css("background-color", "yellow");
});
<table>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
    <td>5</td>
    <td>6</td>
    <td>7contains: Y</td>
    <td>8</td>
  </tr>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

If you want to color the whole body based on whether or not your 7th cell contains a Y, use this:

$(document).ready(function() {
  $("TD:nth-of-type(7):contains('Y')").length && $('body').css("background-color", "yellow");
});
<table>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
    <td>5</td>
    <td>6</td>
    <td>7contains: Y</td>
    <td>8</td>
  </tr>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Prosy Arceno
  • 2,616
  • 1
  • 8
  • 32
  • 2
    This is not doing what you think it is. `$(selector)` always returns an object that is truthy regardless of a match being found or not. The `&&` therefore will always be entered – charlietfl May 19 '21 at 00:45
  • @charlietfl You're right. I should evaluate it to length. Thanks – Prosy Arceno May 19 '21 at 01:58