What is the best way to assign a background color to each tr element using JavaScript?

I have a list of table rows with different background colors like

<tr bgcolor="#OC6110">
<tr bgcolor="#000000">
<tr bgcolor="#FFFFFF">

Is there a way to assign unique background colors to each tr element without specifying its id value in JavaScript or CSS only?

I want to update the background colors dynamically without altering the HTML code that already contains some background color assignments.

Answer №1

If you're looking to generate a random color, you can use the function provided below:

function getRandomColor() {
    var hexValues = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += hexValues[Math.round(Math.random() * 15)];
    }
    return color;
}

To apply the randomly generated color, you can use the following code snippet:

$("tr").each(function() {
    $(this).css("background-color", getRandomColor());
});

For more solutions and the original source, click here.


Update:

If you prefer to store predefined colors in an array, you can do so and then assign them like this:

var myColors = ['#f00','#ff0','#fff']; // Add desired color values to this array

$("tr").each(function() {
   for(var i=0; i<myColors.length;i++){    
     $(this).css("background-color", myColors[i]);
   }
});

Answer №2

give this a shot too

$(function() {
    $("table tr").each(function() {
        var color = 'rgb(' + (Math.floor((256-199)*Math.random()) + 200) + ',' + (Math.floor((256-199)*Math.random()) + 200) + ',' + (Math.floor((256-199)*Math.random()) + 200) + ')';
         $(this).css("background-color", color);
    });
});

Answer №3

Utilizing jquery can be helpful for this task.

$('tr:odd').css("background-color", "#OC6110");

$('tr:even').css("background-color", "#000000");

Answer №4

A great way to retrieve a list of all tr elements is by utilizing the

document.getElementsByTagName('tr')
function. Once you have obtained this NodeList, you can iterate through its elements (similar to an array but with subtle variances) and set attributes such as background color using
setAttribute('bgColor', yourNewTextStringRepresentingAColorHere);

Here is an example implementation:

function colorAllTrs()
{
  var trList = document.getElementsByTagName('tr');
  var i, n = trList.length;
  for (i=0; i<n; i++)
  {
    newColor = '#123456';
    trList[i].setAttribute('bgcolor', newColor);
  }
}

Instead of hardcoding #123456, consider incorporating C-link's getColor function for flexibility in selecting colors.

Answer №5

Check out this JavaScript code snippet.

const colors = ['#999999','#000000','#cccccc'];
    const myTrs = document.getElementsByTagName('tr');

for(let i=0, len = myTrs.length; i < len; i++){
    myTrs[i].style.backgroundColor = colors[i % colors.length]
};

View the Updated Fiddle Demo Here

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

Avoid placing dropdown items within the navbar container in Bootstrap 4

When collapsing the screen, I encountered an issue with the dropdown items being inside the navbar. I positioned the dropdown menu as absolute, but some items were getting cut off, and I didn't want the scroll bar to appear. Despite trying to use medi ...

Toggle button visibility in AngularJS based on checkbox selection

I'm currently utilizing ng-table to construct my table. I have a button positioned at the top of the table that is initially disabled. My goal is to enable this button only when any of the checkboxes are selected. The button should automatically disab ...

Is it possible to refresh a tree without having to reload the entire webpage?

I'm currently developing a web application utilizing zTree library. The tree structure is populated with data retrieved from a Golang backend server. Each leaf node in the tree should have custom icons that can change dynamically while the application ...

Working with a complex JSON structure in JavaScript exemplifies the use of loops

I am currently utilizing json.data.schedules[0].liveVideoList, json.data.schedules[1].liveVideoList, json.data.schedules[2].liveVideoList and so forth. Can someone please guide me on how to implement a loop to retrieve all paths? Here is the code in scri ...

Removing a value from an array contained within an object

I have a scenario in my task management application where I want to remove completed tasks from the MongoDB database when a logged-in user marks them as done. Below is the snippet of code for my Schema. const user = new mongoose.Schema({ username : Str ...

Help needed with debugging CSS for IE6 >_<

I have been working on the following website: www.darksnippets.com While the design looks good on Firefox and Chrome, it appears terrible on IE6. For example, on the home page and other pages like , the width is too wide in IE6. I've been unable to ...

Ways to remove unnecessary div containers in Nuxt js?

This is an example of my page: https://i.sstatic.net/CYCRL.png Showing the Nuxt layout: <template> <div> <Nuxt /> </div> </template> After being compiled by Nuxt, it generates: https://i.sstatic.net/CYdX3.png You ...

The size of the popup does not align properly with the content within it

After creating an extension for Chrome, I specified the dimensions of the popup to be 600 x 300 px. Everything was working perfectly until Chrome updated to version 27. As shown in the screenshot, I set the width and height using CSS, but there is still a ...

Is it possible to create a pie chart using Chart.js with data fetched through an Ajax HTTP GET

Embarking on a new journey here, this week's focus is on delving into Chartjs for canvas and brushing up on JSON usage. The task at hand includes employing an Ajax HTTP GET request to fetch the json file. However, I am currently stumped on how to trig ...

What could be the reason for the checkbox not being selected in a React component

I'm currently working on integrating an autocomplete feature with checkboxes. Learn more here https://i.stack.imgur.com/YtxSS.png However, when trying to use the same component in final-form, I'm facing issues with checking my options. Why is t ...

What is the significance of using the "why" in the href property within the

I need help understanding why the plus "+" is used before and after myUrl in the function .not. Even though it works fine with or without the +, I am curious about why it was included in the code snippet. <script type="text/javascript"> $(documen ...

Retrieve information from a URL and transform it into a JSON array

One of my functions looks like this: function retrieveJsonDataFromWebsite(url, callback) { let chunks = []; return require('https').get(url, res => { res.setEncoding('utf8') .on('data', (chunk) => { ...

jQuery class toggle malfunction

I have a series of list items with specific behavior when clicked: Clicking a list item will select it and add the class .selected If another list item is clicked, the previously selected item becomes unselected while the new one becomes selected If a se ...

jQuery AJAX is seamlessly handling cross domain requests in Chrome and other browsers, however, it seems to be struggling in IE10 as it is not properly transmitting data. Additionally, in Internet

My web application requires sending data to an API hosted on a different domain. The API processes the received data and jQuery AJAX handles the response. This process works smoothly on Chrome and Firefox, but encounters issues on Internet Explorer. While ...

Error message: Unable to locate module (webpack)/hot/emitter when running ionic serve with Ionic 4

Current Technology Stack: Node v10.15.1 Ionic 4.10.1 Upon running ionic serve, an error is encountered: ERROR in (webpack)/hot/emitter.js [ng] Module not found: Error: Can't resolve 'events' in '/zazou/node_modules/@angular-de ...

I have a simple query about rewrite rules

Can someone help with a URL rewrite rule issue I'm having? http://www.mydomain.com/index.html I would like to rewrite the URL above to just: http://www.mydomain.com To clarify, I want to remove the "index.html" part of the URL. Does anyone know ...

Loading images lazily using knockout.js

I have been working on implementing lazy loading for images using knockoutjs binding. I previously successfully implemented lazy loading without the knockoutjs framework, but I am unsure of how to achieve this with knockoutjs binding. Below is my HTML code ...

Validating nested input body objects in NodeJS Express

Struggling with validating nested object request bodies using the "express-validator" package. Imagine a scenario where we are collecting user input with a body structured like this: { "general": { "sessionId": "a2957207-e033-49e7-b9da-1c5f946 ...

Accessing the current instance in Vue when triggered by a checkbox event

Recently, I tested out a to-do-list application built in Vue that has a checkbox feature to mark completed items. I'm looking for a way to access the current instance from the checkbox event. Here's what I've accomplished so far: myObject ...

I am having trouble with $(this) in my jQuery click event handler

When I click my function, I want to change a parent element that contains this function. However, $(this) is not working. What could be the issue? function accountConfirm(message, title, yes_label, no_label, callback) { console.log($(this)); $(&qu ...