pk101
pk101

Reputation: 15

How can I change the background of an element based on a value inside it?

I have a table of numbers - if the number inside the <td> is below a certain number I want to highlight that <td> by making it red by adding a class. My jQuery knowledge is limited but I am pretty sure this is possible to do.

I am using .text() to return the value in the <td>s and .each() to check the numbers one by one.

$(document).ready(function() {

  $(".carpet td").each(function() {
    if ($(this).text() < 5) {
      this.addClass("red")
    }
  });

});
.carpet {
  background-color: aliceblue;
}

.carpet td {
  padding: 12px 20px;
}

.red {
  background-color: #E7295B;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="carpet">
  <tbody>
    <tr>
      <td>2</td>
      <td>7</td>
      <td>4</td>
    </tr>
    <tr>
      <td>3</td>
      <td>4</td>
      <td>5</td>
    </tr>
    <tr>
      <td>2</td>
      <td>1</td>
      <td>1</td>
    </tr>
  </tbody>
</table>

Upvotes: 0

Views: 41

Answers (1)

Taplar
Taplar

Reputation: 24965

Updated your fiddle. You have to parse the text into a number, and fixed the addClass to be off of a jQuery object.

https://jsfiddle.net/9mmqjtk5/12/

$(document).ready(function() {

  $(".carpet td").each(function() {
    if (parseInt($(this).text(), 10) < 5) {
      $(this).addClass("red")
    }
  });

});
.carpet {
  background-color: aliceblue;
}

.carpet td {
  padding: 12px 20px;
}

.red {
  background-color: #E7295B;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="carpet">
  <tbody>
    <tr>
      <td>2</td>
      <td>7</td>
      <td>4</td>
    </tr>
    <tr>
      <td>3</td>
      <td>4</td>
      <td>5</td>
    </tr>
    <tr>
      <td>2</td>
      <td>1</td>
      <td>1</td>
    </tr>
  </tbody>
</table>

Upvotes: 1

Related Questions