I am interested in altering the color of table rows using either JQuery or CSS


Looking to update row colors based on grouping.
For example:

Color the TR accordingly for every 5 rows:
First 5 rows in green (0-4 Rows),
Next five rows in red (5-9 Rows),
Following five rows in yellow (10-14 Rows)
and repeat the pattern...

Answer №1

To achieve the desired effect, you can iterate through each element in the table row using jQuery. Based on the index of each element, you can apply different background colors accordingly. Here's a simple example:

$('#table tr').each(function(index)
{   
    if( index < 5) 
     $(this).css("background-color", "#000000"); //change color code as needed
    else if( index < 10) 
     $(this).css("background-color", "#0000FF"); //change color code as needed
    else if( index < 15) 
     $(this).css("background-color", "#00FF00"); //change color code as needed
  //////continue for other conditions

}); 

Answer №3

Give this a shot - an elegant CSS-only fix.

// Let's start counting from 0 to infinity.
// For n+1
//     0+1 = 1
//     1+1 = 2
//     2+1 = 3
//     ... and so forth...

table tr:nth-child(n+1) {
  color: green;
}
table tr:nth-child(n+6) {
  color: red;
}
table tr:nth-child(n+11) {
  color: yellow;
}

Check out the live demonstration: http://jsfiddle.net/29zrT/

For more in-depth information, visit: http://css-tricks.com/how-nth-child-works/

Answer №4

Check out this modified version of shiplu's code:

var table = document.getElementById("tbl");
rows = table.rows;
var colors = ['yellow', 'green', 'red'];
var groupSize = 5;
var totalColors = colors.length * groupSize;

for(var index=0; index < rows.length; index++){
    rows[index].style.backgroundColor = colors[(index % totalColors) / groupSize | 0];
}

This code will color rows in groups of 5 with the same color. If there are more than 15 rows (number of grouped rows multiplied by number of colors), it will restart the color pattern.

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

Issue with Firefox browser: Arrow keys do not function properly for input tags in Twitter Bootstrap drop down menu

Requirement I need to include a login form inside the dropdown menu with username and password fields. Everything is working fine, except for one issue: Issue When typing, I am unable to use the arrow keys (up/down) in Firefox. This functionality works ...

Customizing jQuery's $.ajax() function to process data received from a PHP file using $_POST variables

Before I ask my question, here is the updated version of my HTML code: <?php $conn = //successfully connected to the database. $sql = "SELECT t1.column1 AS Column_1 FROM table1 t1"; $rs = mysqli_query($conn,$sql); $rows= mysqli_fetc ...

Vue js: Stop Sorting array items; only display the resulting array

I recently came across a tutorial on voting for a Mayoral Candidate. The tutorial includes a sort function that determines the winner based on votes. However, I noticed that the sort function also rearranges the candidate list in real time, which is not id ...

Discovering the process of retrieving API data upon a button click within Next.js using server-side rendering

Hi there, I'm fairly new to working with next.js and would greatly appreciate some assistance. I am trying to figure out how to fetch data from an API upon clicking a button in next.js on the server side. I understand that using onClick directly is ...

When sending an ajax request with HTML data as the payload

While working on an MVC program, I encountered an issue when trying to send data from a TextArea to the controller upon a button click. Everything worked fine until I had HTML-based data inside the TextArea. Here's a snippet of the HTML code: <te ...

Unable to trigger click event

I apologize for asking the same question again, but I'm really struggling with this seemingly easy (or difficult?) code problem. Despite trying out Rory McCrossan's solution from here, it still doesn't seem to work for me. Can someone please ...

The vue-pdf is having trouble loading all pages due to an "undefined property" issue

I am currently utilizing the following technologies: Vue.js, vue-route, Vuetify, Firebase (with a database) and vue-pdf The issue I am facing involves attempting to load all pdf pages using "vue-pdf" plugin. However, when trying to read the pdf, I encoun ...

A flex container containing two divs each with a white-space:nowrap element set at 50% width

How can I create a parent div that contains two child divs, each with a width of 50% that adjusts based on content? The issue arises when one of the child divs has an h3 element with white-space:nowrap;, causing it to exceed the 50% width. I attempted to ...

Is there a way I can retrieve a cookie stored in an Express middleware even if the req.cookies object is returning empty?

I am currently working on validating a cookie using the cookie-parser module to verify if the user is authenticated to access restricted routes within my application. My technology stack includes NodeJS and Express for the server, and Sveltekit for the fro ...

Creating a process to produce a random number and send it directly to an automated email

I'm currently utilizing a form builder from jqueryform.com to construct a registration form. My goal is to have each registered user assigned with a unique account number, which will be a randomly generated 6-digit number. Additionally, I want the pro ...

Obtain the content of a dynamic text input field from a nested directive

I recently developed a custom directive using AngularJS that contains a child directive. The child directive's main task is to create various dynamic input elements like textboxes, radio buttons, and checkboxes, each with default values sourced from a ...

If there are no visible layers, OpenLayers will not recognize zoom scroll events

I have observed that when all OpenLayers.Layers are set to invisible, I lose the ability to zoom in and out using the mousewheel. Although I can still use the OpenLayers.Control.Zoom buttons, the mouse wheel functionality is disabled. Is there a way to de ...

Preventing Text Truncation in THREE.js Texture Created from 2D Canvas

Many people tend to use the 2D canvas texture method for creating text billboards, sprites, and overlays in THREE.js scenes instead of relying on imported image files. You can check out an example by Lee Stemkoski here. However, I have noticed that when a ...

Error message: An uncaught promise was encountered, despite adding a catch function. I am unable to identify the issue causing this error

Why is the added catch block not functioning properly? function maxRequest(url = ``, times = 3) { // closure function autoRetry (url, times) { console.log('times = ', times); times--; return new Promise((resolve, reject) => ...

Passing a variable between two PHP files and then showcasing its value in a separate third file

bookincome.php receives several inputs, and bi.php calculates the total net income based on the values provided by bookincome.php. It then displays a table containing all the user-given values and the calculated total book income ($tnibeforetax) value. How ...

How to send arrays through JSON?

I have some PHP code: $ids = array(1,2,3); $names = array("cat","elephant","cow"); $originalSettings = array ('ids'=>$ids,'names'=>$names); $jsonSettings = json_encode($originalSettings); echo $jsonSettings; Here ...

Invoking a class method in Javascriptcore on iOS

I'm currently trying to comprehend the inner workings of JavascriptCore. Initially, I attempted calling a single function. Now, my focus has shifted to invoking a function within a class. This is what my javascript code looks like: var sayHelloAlf ...

What is the best way to show a label and select box side by side using Angular Material?

I have been trying to keep input and label in the same line using Angular Material, but I haven't found a solution yet. Most of the available solutions are in HTML and CSS, but I specifically need a way using Angular Material. The method I tried invo ...

Tips for utilizing bootstrap.css to position a web design form in the center of the page and place the copyright at the bottom

I have spent several hours trying to figure out how to achieve this, but still haven't found the solution. I have a form that I believe doesn't look very good: So, I attempted to center the form on the page and place the footer.php at the botto ...

Show the value of an array index in JavaScript

Imagine retrieving data from a local API using the code snippet below: {console.log("Bin", this.state.rows.filter(qc => qc.BinsByDayByOrchardsQCs.length > 0).map((bin) => bin))} The output you get may look something like this: 0: {…} ...