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

Using inline style instead of relying on the quill editor's built-in classes, as classes may not be accessible in order to render HTML effectively

I have integrated the ngx-quill editor into my Angular project as the rich text editor. I plan to save the generated HTML in a database and display it on various browsers using innerHTML. Since the styling is done through a class attribute that references ...

Can a Stylus and Node.js with Express project utilize a local image?

Let's talk about using images in a Web app. In my Stylus file, style.styl, I typically set the image using code like this: .background background: url(http://path/to/image) But what if we want to save the image to our local app directory and use ...

Step-by-step guide on integrating Bulma page loader extension as a Vue component

Is there a way to integrate the Bulma-extension page-loader element as a Vue component in my project? I attempted to import page-loader.min.js and use it, but unfortunately, it didn't work as expected. <template> <div class="steps"> ...

AngularJS - Use promise instead of returning a data object

I am currently working on a project using AngularJS. Within my service.js file, I am attempting to retrieve some values. However, instead of receiving the actual data, I am getting back a promise object with some $$variables along with the desired data. ...

Ways to center elements horizontally without relying on Flexbox layout?

Is there a way to arrange the web elements side by side without relying on Flexbox? Although an effective tool, Flexbox does not function properly with IE 9 or 10. I am aiming for the text inside the link to be displayed immediately next to the images. The ...

Express Promises Linked Together: Lack of Data in Last Stage

When handling put requests for my restful API, I utilize the findOneAndUpdate method of Mongoose. The password is left to the second step where the 'save' pre hook of Mongoose is used to hash the password. router.put("/:id", function(req, res, n ...

Changing the name of a tab within a p-tabview

Setting up a p-tabview with tabs containing specific content involves the following code: <p-tabView class="tabmain" > <ng-container *ngFor="let tab of tabs"> <p-tabPanel [header]="tab.header" > ...

What is the best way to use jQuery to find and select an "a" tag that links to a file with a specific

My goal is to select links that have different types of files using jQuery: jQuery('a[href$=".pdf"], a[href$=".doc"], a[href$=".docx"], a[href$=".ppt"], a[href$=".pptx"], a[href$=".xls"], a[href$=".slxs"], a[href$=".epub"], a[href$=".odp"], a[href$=" ...

What is the best way to distribute stroke width evenly on a rounded hexagon in an SVG?

I created a rounded hexagon with stroke width, but the top and bottom curves appear darker. Does anyone know how to evenly distribute the stroke width along the border? Here is my SVG code: <svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewbox ...

Tips on wrapping div elements while maintaining equal width in different screen sizes using @media queries

Does anyone have a solution for wrapping divs using @media screen while maintaining equal width on all divs? I've tried using float and inline-block, but can't seem to achieve consistent justified widths. While table-cells maintain equal field wi ...

The eot file converted online is not functioning as expected

I have tried converting the 'Helvetica Neue Bold' ttf to eot online, but unfortunately it does not seem to work in IE8 and below. The font face I used is as follows: @font-face { font-family: 'HelveticaNeueBold'; src: url(&apo ...

Issue with fullPage.js - Unable to scroll to footer on the last section of the page

I'm currently working with the fullPage.js plugin () and encountering some issues. While sliding through each section, everything functions as expected. However, when I reach the last section and try to scroll down to the footer below it, I encounter ...

Ways to retrieve the final appearance of element m in array n

As a beginner in programming, my goal is to access the last position of element m within array n. The following code displays all positions of element m: var n = []; while (true) { let input = prompt("Please enter a number for the ...

Adding an <a> tag within an <li> element can lead to complications

I'm having trouble inserting an anchor tag into a list item. I can't figure out why it's not working. navListItem = '<li class="p-list-item"></li>'; mainLink = '<a class="main-a" href="' + ...

Issue with SwiperJS not completely filling the height of a div

My issue relates to using swiperJS with multiple images, as I'm struggling to make it take the full width and height of the containing div. Despite applying styling like this to my images: .swiper-slide img { width: 100%; height: 1 ...

Effective strategies for managing form submissions with React and Typescript

As I dive into refactoring my code to TypeScript, especially as I am still getting accustomed to it, I find myself pondering about the HTML element types with React events. This has led me to rethink how I approach form creation and submission event handli ...

Experiencing challenges with ng-repeat and the concept of 'distinct'

I'm facing a perplexing issue. When utilizing ng-repeat to iterate through my data and create checkboxes, I encounter unexpected behavior. The result is multiple duplicate items being displayed instead of unique ones. Here's an example: <lab ...

Locating the Active Object's Coordinates in fabric.js

When using fabric js, I have successfully drawn various shapes like circles and rectangles. However, I encountered an issue while trying to obtain the coordinates of the rectangle using the fabric.rect() method. canvas.getActiveObject().get('points& ...

Tips for implementing a CSS Flexbox layout with varying div heights

I am working on a page that features five unique panels, each with its own distinct height and width. I have been considering implementing CSS Flexbox to ensure these panels stack properly as the page becomes responsive. However, one major issue I've ...

Explore within another map and analyze the node to spot the differences

I have some questions about iterating through a JavaScript Object and using array functions in JavaScript. Let's assume I have the following variables: var json1 = "[{"id": 1, "name":"x"}, {"id": 2, "name":"y"}]"; var json2 = "[{"id": 1, "name":"x"}, ...