Adjust the background color of a column in HTML based on its corresponding color name

Is there a way to change the background color of a column in an HTML table if the value is green? We want the background color to reflect the color name. The data will be retrieved from a web service.

Here is the HTML code used to display the data in the table:

<html>
    <head>
    </head>
    <body>
        <table>
            <tr>
                <th>Risk Category</th>
            </tr>
            <tr>
                <td colspan="1"></td>
            </tr>
        </table>
    </body>
</html>

https://i.sstatic.net/RMWRu.png

Answer №1

To add color to a td element, you can apply inline styling as shown in the example below.

<td style="background-color:COLOR_NAME_OR_HASH_FROM_SERVER"></td>

Answer №2

When the colors returned from the server are not easily interpretable (such as Amber), you may need to include some basic CSS. I have placed it within the <head> section for your convenience, but feel free to transfer it to an external CSS file, especially if there are numerous colors.

If you have the ability to modify the markup, simply add the color provided by the server as a class on that particular cell.

<html>
<head>
    <style>
        .Amber { background: #ffbf00; }
        .Green { background: #008000; }
        .Red   { background: #f00; }
    </style>
</head>
<body>
    <table>
        <tr>
            <th>Risk Category</th>
        </tr>
        <tr>
            <td class="Amber" colspan="1">Amber</td>
        </tr>
    </table>
</body>
</html>

If modifying the markup is not possible for any reason, you will need to iterate through the table cells using JavaScript and assign classes accordingly. You can get started with something like this:

var cells = document.querySelectorAll('td');

for( i = 0; i < cells.length; i++ ){
  text = cells[i].innerText || cells[i].textContent;
  cells[i].className = text;
}

To bring everything together, here's a code snippet demonstrating how to dynamically add classes to the cells based on the color retrieved from the server using JavaScript.

var cells = document.querySelectorAll('td');

for( i = 0; i < cells.length; i++ ){
  text = cells[i].innerText || cells[i].textContent;
  cells[i].className = text;
}
.Amber { background: #ffbf00; }
.Green { background: #008000; }
.Red { background: #f00; }
<html>
    <head>
    </head>
    <body>
        <table>
            <tr>
                <th>Risk Category</th>
            </tr>
            <tr>
                <td colspan="1">Amber</td>
            </tr>
            <tr>
                <td colspan="1">Green</td>
            </tr>
            <tr>
                <td colspan="1">Red</td>
            </tr>
        </table>
    </body>
</html>

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

renewing a div element without the need to reload the entire webpage

I'm currently developing a setup process for configuring a database. My goal is to allow the user to progress through each phase without having to refresh the page. However, I've encountered an issue while trying to implement the .load() function ...

What is the best way to avoid using ng-repeat for the last item being shown?

I currently have an ng-repeat loop that is dependent on an ng-if condition. Here is the specific code block: <div class="fav-prod-customised> <p ng-repeat="ingredient in product.options" ng-if="ingredient.default_quantity == 0 & ...

Placing a Picture in a precise location with the help of jquery

My HTML code created by Apex <tr> <td class="labelCol"> <label for="login_page:signup_form:pb2:j_id5:j_id12">Contact Name</label> </td> <td class="dataCol "> <input name="login_page:signup_form:pb2:j_ ...

JavaScript file slicing leads to generating an empty blob

I am currently working on a web-based chunked file uploader. The file is opened using the <input type="file" id="fileSelector" /> element, and the following simplified code snippet is used: $('#fileSelector').on('change', functio ...

How do I search for a JSON object in JavaScript?

I have an array containing screen resolutions and I need to find the correct resolution range for the user's viewport (I have the width x height of the current window). Here is the sample JavaScript array with JSON objects: [ {width:100,height:200, ...

Sophisticated tree ext-table drag-and-drop functionality (5)

I have been experimenting with using fancytree alongside the ext-table and dnd5 extension. Up to this point, everything has been working smoothly for me. My goal now is to be able to sort the table columns via dnd. Unfortunately, registering the content o ...

Arrange divs next to each other using CSS

I am currently working with a basic layout on my webpage <div id="content-wrap"> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <div ...

Randomly injecting strings like 'jQuery111201xxx' into a string using jQuery Ajax

After implementing a booking system that utilizes FullCalendar, I encountered an unusual issue with the 'notes' field. Occasionally, a strange string is inserted into the notes field at random points. Here's an example of what I found recent ...

What is the formula for determining the size of an image using JavaScript, jQuery, or Java?

I'm looking to determine the dimensions of an image. I have both the image src and base64 data available. My goal is to display the current size of the image. I am working with Java and JavaScript. Is there a way for me to calculate the image size usi ...

Encountered a 404 error while handling the Express 4 module, indicating that the 'html' module could not be

I need to update my express app to handle 404 (and 500) errors by displaying HTML instead of plain text. I have been able to show text to the client for 404 errors, but now I want to show HTML instead. My 404.html file is located in the /app directory. Cu ...

"Integrating Associated Models with Sequelize: A Step-by-Step Guide

I am attempting to retrieve all transactions along with their associated stripePayments, but I keep encountering the error include.model.getTableName is not a function. In my database schema, there is a table for transactions that has a one-to-many relati ...

In the virtual playground of Plaid's Sandbox, how can I replicate a fresh transaction and detect it using the Webhook feature?

Is there a way to trigger a simulated transaction within the webhook instead of just a DEFAULT_UPDATE event? I'm trying to find a way to simulate an actual transaction so that I can test my webhook integration. I've searched through the sandbox ...

I am interested in creating a class that will produce functions as its instances

Looking to create a TypeScript class with instances that act as functions? More specifically, each function in the class should return an HTMLelement. Here's an example of what I'm aiming for: function generateDiv() { const div = document.crea ...

What could be the reason my website is not saving the user input information to the database?

Hello! I am a novice programmer attempting to create a basic registration function on my website. I have set up a simple form for users to input their information, but I am facing an issue where the user data is not being stored in my database. ...

How to select a child element within a sibling div of a parent div using jQuery

HTML <div class="container-fluid"> <div class="input-page">...</div> <!-- field 1 --> <div class="col-md-12 col-sm-12 col-xs-12 no-padding">...</div> <div class="col-md-12 col-sm-12 col-xs-12 no-padding"> ...

Conditional rendering of Materialize navbar links

I am currently working with React Materialize and React Router Dom. My goal is to display navlinks only to authenticated users using conditional rendering. However, when I implement it as shown below, the navlinks are displayed vertically instead of hori ...

Maximizing values entered into form fields

Looking for a way to extract the highest number from a set of input fields in an HTML form using JavaScript? Take this example: <input id="temp_<strong>0</strong>__Amount" name="temp[<strong>0</strong>].Amount" type="text" valu ...

Nuxt Page Featuring One Exclusive Product

I am just getting started with Nuxt and I'm in the process of creating a Single Product. I have some questions: How can I generate multiple pages using SSR and create a unique HTML for each page? Should CSR be developed first before implementing SSR, ...

Separate each menu item by using the pipe symbol within the list tags

Can you help me style the menu list in CSS by adding a separator | between each element? I attempted using content: "|", but it didn't produce the desired outcome. The current look of the menu is as follows: <ul> <li><a href="..."& ...

The Chrome Keyboard on Android seamlessly passes words to the next input field when the focus changes in JavaScript

When using two input fields, pressing the enter key on the first field in Chrome (49) on Android (6.0.1) carries over the last word typed to the new input due to the right-bottom button on the standard keyboard. Is there a way to prevent this behavior or a ...