Tips for modifying the background color of an individual row within a table using the Document Object Model (DOM)

I am trying to change the color of each row in a table only if the text inside the 4th cell is "DELAYED". I have created a function for this purpose, but the color is not changing as expected...

function assignColor()
{
    //retrieve all tr elements from the document
    var x = document.getElementsByTagName("tr");

    for(var i = 0; i < x.length; i++)
    {
        //Check if the text content in the 4th cell of the tr is "DELAYED"
        if(x[i].cells[3].textContent == "DELAYED")
        {
            x[i].style.backgroundColor = "red";
        }
    }

}

I suspect there might be an issue with how I am populating the table from JavaScript to HTML.

function printFlights(arrayOfFlight)
{
    //Add tr elements based on the length of the array
    for(var i = 0; i < arrayOfFlight.length; i++)
    {

        //create a tr element
        var tr = document.createElement("tr");

        //Insert cells into the tr using object properties

        tr.insertCell(0).innerHTML = 
        formatDate(arrayOfFlight[i].arrivalDate);
        tr.insertCell(1).innerHTML = 
        formatTime(arrayOfFlight[i].arrivalDate);
        tr.insertCell(2).innerHTML = arrayOfFlight[i].destination;
        tr.insertCell(3).innerHTML = arrayOfFlight[i].status;
        tr.insertCell(4).innerHTML = arrayOfFlight[i].airplane;
        tr.insertCell(5).innerHTML = arrayOfFlight[i].gate;

        //add tr to tbody
        tableBody.appendChild(tr);
    }
}

Answer β„–1

It appears that your code is functioning correctly, with one caveat - if there is any whitespace present in the <td> elements within your HTML (as shown in the demo below), then it is necessary for your code to utilize the .trim() method to trim the content of the cells before performing the string comparison.

Refer to the example below:

function assignColor() {
  var x = document.getElementsByTagName("tr");

  for (var i = 0; i < x.length; i++) {
    if (x[i].cells[3].textContent.trim() == "DELAYED") {
      x[i].style.backgroundColor = "red";
    }
  }
}

assignColor();
<table border="1">
  <tr>
    <td>
      Col 1
    </td>
    <td>
      Col 2
    </td>
    <td>
      Col 3
    </td>
    <td>
      Col 4
    </td>
  </tr>
  <tr>
    <td>
      Col 1
    </td>
    <td>
      Col 2
    </td>
    <td>
      Col 3
    </td>
    <td>
      DELAYED
    </td>
  </tr>

Answer β„–2

Success! Your code is functioning properly:

function updateColorScheme()
{
    // Retrieving all the tr elements from the document
    var rows = document.getElementsByTagName("tr");

    for(var i = 0; i < rows.length; i++)
    {
        // Checking the text content in the 4th cell of each tr
        if(rows[i].cells[3].textContent == "DELAYED")
        {
            rows[i].style.backgroundColor = "red";
        }
    }

}
updateColorScheme();
<table>
<tr>
  <td>a</td>
  <td>a</td>
  <td>c</td>
  <td>DELAYED</td>
</tr>
</table>

Answer β„–3

Give this method a try, it will highlight any cell with the text "DELAYED".

function highlightDelayedCells() {
  var cells = document.querySelectorAll('tr td');

  for(var i = 0; i < cells.length; i++) {
    if(cells[i].textContent === "DELAYED") {
      cells[i].style.backgroundColor = "red";
    }
  }
}
<table>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>DELAYED</td>
  </tr>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>DELAYED</td>
  </tr>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>DELAYED</td>
    <td>4</td>
  </tr>
</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

Automatically launching a new tab upon page load in a React application

I have a specific requirement that when a form is loaded, a new browser tab should automatically open with a URL based on one of the attributes. After researching some solutions on various platforms like Stack Overflow, I came across this helpful thread: M ...

Issue with Auth0 not properly redirecting to the designated URL in a React application

auth.js import auth0 from 'auth0-js'; export default class Auth { constructor() { this.auth0 = new auth0.WebAuth({ domain: '<properURL>', clientID: '<properID>', re ...

Clicking on a checkbox within an HTML table that incorporates handlebar and Express.js

My situation involves a HTML table within a form that is being populated with Handlebars. I need to be able to select certain rows in the table using checkboxes, and upon form submission through a POST request in an Express.js framework, I require the JSON ...

What is the reason that jQuery does not work on HTML generated by JavaScript?

One of my JavaScript functions, named getImages, is responsible for loading the following HTML structure: // Function starts here function getImages() { $.getJSON(GETIMAGELIST, function(data) { var items = []; // Populating the HTML $.each(dat ...

Removing specific characters from HTML code with ASP

Can someone help me understand how to make the page display HTML code while excluding specific characters like this one (ΓΌ)? ...

Optimizing table cell width in ASP.NET based on longest text content

Software: Visual Studio 2010, Asp.Net 4.0 I am working with multiple tables that are stacked vertically on top of each other, all generated dynamically in the codebehind. I would like to ensure that the first column in each table is the same width, based ...

Authentication in HTML5 beyond the internet connection

Seeking feedback on the most effective way to control access to an HTML5 application that is primarily used offline. This application utilizes IndexedDB, local, and session storage to securely store data for offline use, all served via HTTPS. The main go ...

Is it possible to utilize PDF.js once the PDF file has been downloaded?

My goal is to integrate PDF.js (or Viewer.js) with a Flask application, where I have already retrieved the file from a server. Instead of using PDFJS.getDocument('helloworld.pdf') I prefer to display the downloaded PDF in the browser through a ...

Google Analytics Experiments implemented on the server-side

Curious about the necessity of including the JavaScript cxApi when conducting experiments server-side. Is it possible to send the selected experiment and variations using PHP, or perhaps by injecting a JavaScript snippet internally (without relying on exte ...

Making changes to a JSON file using JavaScript

Hello everyone, I am a beginner in Javascript and have successfully created a system that allows me to search and filter users in my data.json file. However, I am now looking to develop an application that can add users to the data.json file. Any advice or ...

"Resetting count feature in AngularJS: A step-by-step guide

I have a list consisting of four items, each with its own counter. Whenever we click on an item, the count increases. I am looking to reset the counter value back to zero for all items except the one that was clicked. You can view the demonstration here. ...

Obtain JSON information by submitting an HTML form using an HTTP POST request

Looking to retrieve JSON data with the click of a button Here's the HTML code: <html> <title> </title> <body> <h2> Main API - http://api.kalendern.se/api</h3> <form method="get" enctype="applica ...

Issue with deploying Azure node.js application due to libxmljs error

My goal is to launch my website using libsmljs built on node.js on Windows Azure. However, during the deployment process on Azure, I encounter a failure with the following error message: Command: C:\DWASFiles\Sites\CircuitsExpress\Virt ...

Is Q.js capable of functioning independently from node.js and require()?

Currently experimenting with the latest version of q.js to integrate promises into my ajax calls without utilizing node.js at all. I retrieved the most recent version from https://github.com/kriskowal/q and only included q.js in my project. While testing, ...

Alignment of label not remaining centered vertically, issue with bootstrap

Struggling with getting this label to stay centered vertically? It always seems to appear at the top. Any help would be greatly appreciated. Thank you! Check out the code here <div class="container"> <div class="row"> <div clas ...

"Implementing unique typefaces on a static website hosted on AWS

I've been attempting to incorporate a unique font into my CSS class using font-face. I have experimented with both .otf and .ttf file formats, uploading the custom font files to an S3 bucket. I made sure to grant public permissions to the font files a ...

Having difficulty specifying numerical entries only

I have been attempting to create an input field that only accepts numbers, but for some reason it still allows letters to be entered. Why is this happening? <input type="number" pattern="[0-9]" ...

Stop processing the current websocket connection once a new websocket request is received

Currently, I am utilizing the npm ws module (or its wrapper named isomorphic-ws) for establishing a websocket connection. NPM Module: isomorphic-ws This setup allows me to retrieve an array of data from a websocket++ server situated on the same local mac ...

Unable to achieve separation of borders within dash_table.DataTable styling using CSS by setting border-collapse: separate; considering using border-spacing instead

Is there a way to create space between the lines of a table in dash_table.DataTable using css or regular style capabilities? I have tried using border-collapse and border-spacing but it doesn't seem to be working. How can I achieve this desired spacin ...

Perform an ajax request to check for the existence of an image and insert

I've been trying to implement asynchronous JavaScript based on guidance from this answer, but I'm facing some difficulties in understanding where things are going wrong. My goal is to use autocomplete functionality to request specific files from ...