Using HTML to dynamically alter a row's background color depending on its value

I have a table within an HTML page that I would like to color all rows in red when the first column reaches a specific value.

After researching on StackOverflow, I found suggestions to add these two attributes (border-collapse and border-spacing) to my table:

<table id="my-table" style="border-collapse:collapse; border-spacing:0 1px">

Now, how can I use JavaScript to set the background color based on a new value?

I attempted the following approaches:

 if (value == 'broken') {my-table[i].css('background-color','red');} // OR   
 if (value == 'broken') {my-table[i].cells.style.background = 'red';}

where i is the index of the row I am targeting. However, no changes are visible! Can anyone provide me with advice? Thank you.

Answer №1

Here is an example showcasing a tutorial on navigating a grid...

Feel free to customize this example to suit your needs...

You can also utilize the table Object for similar tasks...


  <!doctype html>
  <html lang="en">
  <head>
    <meta charset="UTF-8>
    <title>Grid Navigation</title>
    <style>
      td{width:10px;height:10px;background:#ddd;}
      tr:nth-child(5) td:nth-child(5){background:#f00;}
    </style>
  </head>
  <body>
    <div id="gridContainer">
    </div>
    <script>
      
      var row=col=5,max=10;
      gridContainer.innerHTML = '<table>'+('<tr>'+'<td>'.repeat(max)).repeat(max)+'</table>';
      window.addEventListener("keyup", function(e){
        var colDiff, rowDiff;
        var keyMap = new Map([[37,[-1,0]],[38,[0,-1]],[39,[1,0]],[40,[0,1]]]);
        if (keyMap.has(e.keyCode)){
          document.querySelector(`tr:nth-child(${row}) td:nth-child(${col})`).style.background='#ddd';
          [colDiff,rowDiff]=keyMap.get(e.keyCode);
          row+=rowDiff;
          col+=colDiff;
          row = (row>max) ? max : (row < 1) ? 1 : row;
          col = (col>max) ? max : (col < 1) ? 1 : col;
          document.querySelector(`tr:nth-child(${row}) td:nth-child(${col})`).style.background='#f00';
        }
      }) 
    </script>
    
  </body>
  </html>

Answer №2

Optimize your code by utilizing document.getElementById along with a variable to simplify the process.

For example:

 let tableRows = document.getElementById("tableID").getElementsByTagName("tr");
 tableRows[index].style.backgroundColor = "blue";

Don't forget to monitor your console for any potential errors and confirm that the value of index is correct and properly assigned.

Answer №3

To change the background color of a specific row, you will need to apply CSS styles to the tr element. Without further information on where the variable value is declared, it's difficult to provide a precise code example.

Here is an instance where I determine if a row should be marked as "broken" based on a data attribute assigned to the tr:

$("tbody tr", $("#my-table")).each(function() {
  var tr = $(this);

  if (tr.data("broken") == true) {
    tr.css({
      "background-color": "red"
    })
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="my-table" style="border-collapse:collapse; border-spacing:0 1px">
  <thead>
    <tr>
      <th>Header 1</th>
      <th>Header 2</th>
    </tr>
  </thead>
  <tbody>
    <tr data-broken="true">
      <td>Value 1</td>
      <td>Value 2</td>
    </tr>
    <tr>
      <td>Value 1</td>
      <td>Value 2</td>
    </tr>
    <tr>
      <td>Value 1</td>
      <td>Value 2</td>
    </tr>
  </tbody>
</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

Attempting to implement a basic AngularJS integration with Google Maps for a straightforward demonstration

I have a basic Google Maps project that I am trying to transition into an AngularJS project. This is all new to me as I am a beginner in both AngularJS and web development so please bear with me :) The project can be found at https://github.com/eroth/angul ...

Is there a way to extract the content from a dynamic textbox using a dynamic button in HTML and AJAX?

My current task involves fetching data from a database and updating the records individually. I have created a table with a text input field and a button that will be generated dynamically for each record. The text input field is populated with the previou ...

Responsive SVG curve line design

Trying to position the SVG line in the center with the SVG icon, without overlapping them. Need a responsive solution that adapts to the container width. Any suggestions involving canvas or after pseudo classes? The line and icon should always be centere ...

Module Not Found Error: Electron and Typescript Collaboration

I am currently facing an issue while attempting to build my electron application using typescript generated from the electron-quick-start-typescript project. I have included an additional module named auth.ts, but unfortunately, it is not being recognized ...

Create a complete duplicate of a Django model instance, along with all of its associated

I recently started working on a Django and Python3 project, creating a simple blog to test my skills. Within my project, I have defined two models: class Post(models.Model): post_text = models.TextField() post_likes = models.BigIntegerField() post_ ...

Examining the code - I'm having trouble locating the origin of its creation

My question might seem trivial and I could figure it out on my own, but for some reason, it's just too difficult for me. I can easily find details like the width and height of a div, the background color, and the font used. However, what I can't ...

Guide on Implementing Right-to-Left (RTL) Support in Material UI React

Currently, I am in the process of developing an application designed for LTR usage, but I am interested in adding RTL support as well. The application itself is built on top of Material UI React. By using CSS Flex Box, I have managed to rotate the applicat ...

Modifying or enhancing a jQuery method

As a newcomer to jquery, I may not have the exact terminology down pat, but I am looking to either override or extend a function in a jquery .js file that is included on all our pages by the lead developer in our team. Currently, the existing function in ...

Tips for extending the space between one element and another when the width decreases:

Currently in the process of building a website using HTML/CSS/JS and have run into an issue. My front page features an image with text overlay, where the image has 100% width and a fixed height of 487px. I positioned the text using position:relative; and t ...

Is your overlaying div functioning properly in Chrome and Firefox, but encountering issues in Internet Explorer?

I am facing a challenge with overlaying two divs on top of an image. My objective is to create a simple lightbox where when the user hovers over the left or right side, the cursor changes to a pointer and arrows appear. Below is the code I am using: HTML: ...

I am experiencing an issue with the Search Filter where it is not successfully removing

My goal is to filter colors when a user searches for a color code. Currently, the search function displays the correct number of filtered items, but the color bubbles are not being removed as intended. I am working on removing the bubbles when a search is ...

Another component's Angular event emitter is causing confusion with that of a different component

INTRODUCTION In my project, I have created two components: image-input-single and a test container. The image-input-single component is a "dumb" component that simplifies the process of selecting an image, compressing it, and retrieving its URL. The Type ...

Align a component vertically in a FlexBox using Material UI

I have a React app where I created a card with specified min width and height, containing only a header. I want to add flexbox that occupies the entire left space with justify-content="center" and align-items="center". This way, when I insert a circular pr ...

Executing Actions Prior to Redirecting

I am working on implementing a timer process using a custom JQuery plugin that will redirect to the login page after a specific number of minutes. Additionally, when the timer reaches zero, I need to execute a task, which in this case involves making a cal ...

Transitioning background with background sizing set to cover

I have been searching for an answer to this question, but haven't found one yet. Currently, I have a series of divs with background-images set to 'background-size: cover'. My goal is to make the images zoom in and grow on hover. However, i ...

Placing a video as the background of a div element and ensuring the text appears in the

I'm facing a challenge with setting my text background as a video. Despite my efforts, the text remains hidden behind the video and doesn't come to the front. Additionally, I'm encountering an issue where the video background does not adapt ...

In what way is the background-color of WindowInfoBackground utilized?

I attempted to implement background-color : WindowInfoBackground;. The property background-color : WindowInfoBackground; allows for the assignment of the system color to the background-color attribute. Despite using this particular value, the backgroun ...

Nuxt with Laravel API Integration

I am working on pulling in two separate data sets within the store directory. I plan to create a categories list and an events list. Initially, I began with a single set in the index.js file. export const state = () => ({ categories: [] }) e ...

Quirky Behavior of an Array of Objects

const allocation = [ {partner: 3}, {partner: 1}, {partner: 2}, {partner: 0}, {partner: 4} ]; const rightallocation = new Array(5); rightallocation.fill({number: 1}); for (let i = 0; i < allocation.length; i++) { const rightIndex = a ...

Background image spacing

Can anyone explain why there is extra space after my background image in this code snippet? (red line in image highlights the spacing issue) Even though the background image doesn't have this space, it seems to extend beyond where the black color ends ...