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>

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>

2

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>

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>

When creating a TR Element, set its className to the user.Status value:

const el = (sel, par = document) => par.querySelector(sel);
const elNew = (tag, prop) => Object.assign(document.createElement(tag), prop);

const getUsers = async () => {
  let users = [];
  try {
    const res = await fetch("https://dummyjson.com/c/38f5-f39a-411e-aeb0");
    const data = await res.json();
    users = data.data;
  } catch (err) { console.error(err); }
  return users;
};

const drawUsersData = async () => {
  const elData = el("#data");
  const users = await getUsers();
  const rows = users.map((user) => {
    return elNew("tr", {
      className: user.Status,
      innerHTML: `
         <td>${user.Name}</td>
         <td>${user.Address}</td>
         <td>${user.Status}</td>
       `
    });
  });
  
  elData.innerHTML = "";
  elData.append(...rows);
};

drawUsersData();
table {
  border-collapse: collapse;
}

td,
th {
  border: thin solid black;
  padding: 0.2rem;
}

tr.Accepted {
  color: green;
}
<table class="table">
  <thead>
    <tr>
      <th>Name</th>
      <th>Address</th>
      <th>Status</th>
    </tr>
  </thead>
  <tbody id="data"></tbody>
</table>

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa

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>

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>

2

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>

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>

When creating a TR Element, set its className to the user.Status value:

const el = (sel, par = document) => par.querySelector(sel);
const elNew = (tag, prop) => Object.assign(document.createElement(tag), prop);

const getUsers = async () => {
  let users = [];
  try {
    const res = await fetch("https://dummyjson.com/c/38f5-f39a-411e-aeb0");
    const data = await res.json();
    users = data.data;
  } catch (err) { console.error(err); }
  return users;
};

const drawUsersData = async () => {
  const elData = el("#data");
  const users = await getUsers();
  const rows = users.map((user) => {
    return elNew("tr", {
      className: user.Status,
      innerHTML: `
         <td>${user.Name}</td>
         <td>${user.Address}</td>
         <td>${user.Status}</td>
       `
    });
  });
  
  elData.innerHTML = "";
  elData.append(...rows);
};

drawUsersData();
table {
  border-collapse: collapse;
}

td,
th {
  border: thin solid black;
  padding: 0.2rem;
}

tr.Accepted {
  color: green;
}
<table class="table">
  <thead>
    <tr>
      <th>Name</th>
      <th>Address</th>
      <th>Status</th>
    </tr>
  </thead>
  <tbody id="data"></tbody>
</table>

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật