skip to Main Content

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>

3

Answers


  1. In order to change the row color as per the status value, you can add conditional logic while generating the rows. Also you can apply the appropriate CSS class or inline styles to the <tr> element depending on the status.

    fetch("some url").then(
      res => {
        res.json().then(
          data => {
            if (data.data.length > 0) {
              var temp = "";
              data.data.forEach((itemData) => {
                let rowColor = itemData.Status === "Accepted" ? "green" : "red";
                temp += `<tr style="background-color: ${rowColor};">`;
                temp += `<td>${itemData.Name}</td>`;
                temp += `<td>${itemData.Address}</td>`;
                temp += `<td>${itemData.Status}</td></tr>`;
              });
              document.getElementById('data').innerHTML = temp;
            }
          }
        );
      }
    );
    
    <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>
    
    Login or Signup to reply.
  2. 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>
    Login or Signup to reply.
  3. Here is a simpler method using template literals since you use innerHTML anyway.

    const url = "https://dummyjson.com/c/38f5-f39a-411e-aeb0";
    const tBody = document.getElementById('data');
    fetch(url)
      .then(res => res.json())
      .then(({data}) => tBody.innerHTML = data
        .map(itemData => `<tr class="${itemData.Status==='Accepted' ? 'green' : 'red'}">
        <td>${itemData.Name}</td>
        <td>${itemData.Address}</td>
        <td>${itemData.Status}</td>
        </tr>`).join('')
      )
    table {
      border-collapse: collapse;
    }
    
    td,
    th {
      border: thin solid black;
      padding: 0.2rem;
    }
    
    .green {
      background-color: green;
    }
    
    .red {
      background-color: red;
    }
    <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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search