Adjust the color of a specific cell within a table using JavaScript

I am looking to dynamically change the row color based on the content of a <td> tag using only HTML, CSS, or JS within my current application setup that does not support external src. Below is the code snippet:

table { 
  width: 750px; 
  border-collapse: collapse; 
  margin:20px auto;
}
tr:nth-of-type(even) { 
  background: #eee;
}
tr:hover {
  background-color:#f5f5f5;
}
th { 
  background: #1489b8; 
  color: white; 
  font-weight: default; 
}

td, th { 
  padding: 10px; 
  border: 3px solid #ccc; 
  text-align: center; 
  font-size: 15px;
}
h3, p{
  text-align: center;
}
<head>
  <h3>Hi User,</h3>
  <p>An alert is created. Following are the details.</p>
</head>
<table style="width:100%">
  <thead>
    <tr>
      <th> Description</th>
      <td>working</td>
    </tr>
    <tr>
      <th>Parameter</th>
      <td>Shutdown</td>
    </tr>
    <tr>
      <th>Machine </th>
      <td>ABC</td>
    </tr>
    <tr>
      <th> Type</th>
      <td>Sensor Machine</td>
    </tr>
    <tr>
      <th> Severity</th>
      <td>Low</td>
  </thead>
</table>

In the above example, when the last <td> tag contains the text "Low", I want the row color to change to green. If it contains "Medium", the color should change to yellow. Is there any way to achieve this?

Answer №1

If you're looking for an easy way to style specific elements in your table based on their content, consider using Javascript and the querySelectorAll method. This allows you to target all the td elements in your table, check their textContent, and apply styling based on certain conditions.

For example, you can use an if condition to match the severity levels of the content and then apply background color styles accordingly.

Check out this live working example:

let getTds = document.querySelectorAll('table td')

getTds.forEach(function(row) {
  //Low
  if (row.textContent == 'Low') {
    row.style.background = 'green'
  }
  //Medium
  if (row.textContent == 'Medium') {
    row.style.background = 'yellow'
  }
})
table {
  width: 750px;
  border-collapse: collapse;
  margin: 20px auto;
}

tr:nth-of-type(even) {
  background: #eee;
}

tr:hover {
  background-color: #f5f5f5;
}

th {
  background: #1489b8;
  color: white;
  font-weight: default;
}

td,
th {
  padding: 10px;
  border: 3px solid #ccc;
  text-align: center;
  font-size: 15px;
}

h3,
p {
  text-align: center;
}
<head>
  <h3>Hi User,</h3>
  <p>An alert is created. Following are the details.</p>
</head>
<table style="width:100%">
  <thead>
    <tr>
      <th> Description</th>
      <td>working</td>
    </tr>
    <tr>
      <th>Parameter</th>
      <td>Shutdown</td>
    </tr>
    <tr>
      <th>Machine </th>
      <td>ABC</td>
    </tr>
    <tr>
      <th> Type</th>
      <td>Sensor Machine</td>
    </tr>
    <tr>
      <th> Severity</th>
      <td>Low</td>
    </tr>

  </thead>

  <thead>
    <tr>
      <th> Description</th>
      <td>working</td>
    </tr>
    <tr>
      <th>Parameter</th>
      <td>Shutdown</td>
    </tr>
    <tr>
      <th>Machine </th>
      <td>ABC</td>
    </tr>
    <tr>
      <th> Type</th>
      <td>Sensor Machine</td>
    </tr>
    <tr>
      <th> Severity</th>
      <td>Medium</td>
    </tr>

  </thead>
</table>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilitarian pool method yields the output from the specified callback function

As a beginner in nodejs, I am currently experimenting with generic-pool and mariasql. My code is functioning well. However, I recently enclosed my code within a function, and I am unsure about the proper way to handle events in nodejs to retrieve the resul ...

What causes the error "Why am I receiving a "Cannot read property 'length' of undefined" when looping through a pug template?

Currently, I am in the process of developing a project using Node and Express. My objective is to have the home page display signup and login links in the nav bar when the user is not logged in. Initially, everything seemed to be working fine, and I was ab ...

Receiving an error message stating "Uncaught SyntaxError: Unexpected token <" in React while utilizing the AWS SDK

Each time I execute 'npm run build' in main.js, an error keeps popping up: Uncaught SyntaxError: Unexpected token < The error vanishes after refreshing the page. Upon investigation, I discovered that two libraries are causing this problem: ...

What is the best way to trigger a sound to play once when the document is loaded?

I was looking for an easy and straightforward method to play a sound as soon as the document is loaded. After browsing through various online resources, I couldn't find a clear explanation. Can someone please assist me on how to create this in a brow ...

Manipulate HTML Elements with a Click of a Button in React

Is there a straightforward method to replicate this jQuery example using only React, without relying on jQuery or other external libraries? I'm still developing my ReactJS skills and hoping for guidance on dynamically creating and deleting elements. ...

Displaying Images in VUE JS from an Array

I'm currently working on linking images to an img element from an array of objects. While I've successfully managed to transfer the strings to the HTML elements, I'm facing challenges with displaying the pictures. Any assistance would be gre ...

Trigger a series of child functions upon clicking the parent button

I am facing an issue where I am attempting to trigger the functions of each child component from a button click event on the parent component. I have tried using props and setting up a new function in the componentDidMount lifecycle method, but only the la ...

Using the https module in Node.js to transfer a file to a PHP server

What is the best method to send an HTTP post request that includes a jpg file to a php server using the node https module? I attempted to use the request module, but it is unreliable (timing out most of the time) and already deprecated. Here is the functi ...

To link circles vertically with a line and fill them with color when clicked, follow these steps:

I am looking to create a design similar to the image below using unordered list items. When a user clicks on a list item, I want the circle to fill with color. I have structured it by creating a div with nested list items and span elements. If a user click ...

Issue with ngClass not updating during Route Event

I am using a bottomNavigation component that changes its style to indicate which route we are currently on. Below is the template for the bottom-navigation: class="menu-icon" [ngClass]="{ 'active-item': buttonActivated.value == '/my-goa ...

NodeJS: The module failed to automatically register itself

Exploring the capabilities of IBM Watson's Speech to Text API, I encountered an issue while running my NodeJS application. To handle the input audio data and utilize IBM Watson's SpeechToText package, I integrated the line-in package for streami ...

unable to comprehend the remaining section

My divs are not checking/unchecking properly. The else part of my code is unable to read it and displays 'undefined'. Please assist me... (The first click works correctly but the second click shows 'undefined') import React, { useState ...

What is the best way to detect input events from the Stripe cardElement to determine if a card is invalid and then proceed to disable the button?

While my user fills out the form with order information and customer details, I ensure that the submit button remains disabled until all validations are met. The library being used for this purpose is express-validate. In addition to the current setup, I ...

Automated Copy and Paste Feature - JavaScript using Ajax

I am working on a unique auto-increment IMDB ID grabber that retrieves the ID as you type the name of a TV show. Currently, I have managed to create functionality where it checks if the field is empty; if not, it displays a button that directs you to a pag ...

How do I connect to a different application's view?

When working with a view that has tiles, I am looking to click on one of them and be directed to a different application that I have created. In typical cases, I would specify the view folder for navigation. However, when attempting something similar for ...

Searching for a specific row of data by ID in a massive CSV file using Node.js

Can someone recommend an npm package that is ideal for iterating over a csv file, locating a specific value, and updating/appending to that particular row? I don't have any code to display at the moment as I'm in the process of testing different ...

What could be causing the div to not respond to ngAnimate?

Recently, I encountered an issue with adding animations to a list of <div>'s in my webapp. After incorporating ngAnimate into the app.js file and including ng-animate="'animate'" in the <div>, I was disappointed to find that the ...

What's the reason behind JavaScript's Every method not functioning properly?

I'm struggling to understand why the array method 'every' is not functioning properly in my project (working on a roguelike dungeon crawler game). Here's an example of the array of objects I am working with: { x: newrm.x, ...

The outcome of a MySQL query involving JSON_OBJECT() is a string value

I have crafted a query that extracts posts from a table and includes information about each post's author: SELECT post.id, post.text, post.datetime, JSON_OBJECT( 'username', user.username, 'firstName', user.firstName, 'last ...

Best practices for utilizing JSON data to maximize its value

When using node.js version 6.10 console.log("retrieved data1 " + body); // returns: retrieved data1 "{'response' : 'Not latest version of file, update not performed'}" I am attempting to extract the Not latest version of file, update ...