javascripthtmlcssfetch-apiinnerhtml

Change html table color based on the value of a cell


I am fetching data from an API and displaying it in a html table. Now I want to change the color of the rows based on the value of a column. For example if status is Accepted then green row and if status is not accepted then red color row.

const url = "https://dummyjson.com/c/38f5-f39a-411e-aeb0";

fetch(url).then(
  res => {
    res.json().then(
      data => {
        //console.log(data.data);
        if (data.data.length > 0) {
          var temp = "";
          data.data.forEach((itemData) => {
            temp += "<tr>";
            temp += "<td>" + itemData.Name + "</td>";
            temp += "<td>" + itemData.Address + "</td>";
            temp += "<td>" + itemData.Status + "</td></tr>";
          });
          document.getElementById('data').innerHTML = temp
        }
      }
    )
  }
)
table {
  border-collapse: collapse;
}
td,th {
  border: thin solid black;
  padding: 0.2rem;
}
<div class="container">
<table class="table">
  <thead>
    <tr>
      <th>Name</th>
      <th>Address</th>
      <th>Status</th>
    </tr>
  </thead>
  <tbody id="data">
  </tbody>
</table>
</div>


Solution

  • To dynamically change the row color in a table based on the value of a particular column, you can follow the approach below. I have used the JSONPlaceholder REST API for testing purposes, but the idea remains the same for any API.

         fetch("https://jsonplaceholder.typicode.com/todos")
            .then((response) => {
              if (response.ok) {
                return response.json();
              } else {
                throw new Error("API request failed");
              }
            })
            .then((data) => {
              if (data.length > 0) {
                let temp = "";
                data.forEach((itemData) => {
                  const rowClass = itemData.completed
                    ? "completed-row"
                    : "not-completed-row";
    
                  temp += `<tr class="${rowClass}">`;
                  temp += `<td>${itemData.id}</td>`;
                  temp += `<td>${itemData.title}</td>`;
                  temp += `<td>${itemData.completed}</td></tr>`;
                });
    
                document.getElementById("data").innerHTML = temp;
              }
            })
            .catch((error) => console.log("Error fetching data:", error));
          .completed-row {
            background-color: green;
            color: white;
          }
    
          .not-completed-row {
            background-color: red;
            color: white;
          }
        <div class="container">
          <table class="table">
            <thead>
              <tr>
                <th>Id</th>
                <th>Title</th>
                <th>Completed</th>
              </tr>
            </thead>
            <tbody id="data"></tbody>
          </table>
        </div>