Choose every fourth row in the table

Is there a way to alternate the background colors of selected groups of 4 rows in a table? I want to make one group red and the next group blue. Any suggestions or ideas on how to achieve this?

<table>
  <tr style="background-color: red;">
    <td>NAME</td><td>AGE</td>
  </tr>
  <tr style="background-color: red;">
    <td>NAME</td><td>AGE</td>
  </tr>
  <tr style="background-color: red;">
    <td>NAME</td><td>AGE</td>
  </tr>
  <tr style="background-color: red;">
    <td>NAME</td><td>AGE</td>
  </tr>
  
  <tr style="background-color: blue;">
    <td>NAME</td><td>AGE</td>
  </tr>
  <tr style="background-color: blue;">
    <td>NAME</td><td>AGE</td>
  </tr>
  <tr style="background-color: blue;">
    <td>NAME</td><td>AGE</td>
  </tr>
  <tr style="background-color: blue;">
    <td>NAME</td><td>AGE</td>
  </tr>
  
  <tr style="background-color: red;">
    <td>NAME</td><td>AGE</td>
  </tr>
  <tr style="background-color: red;">
    <td>NAME</td><td>AGE</td>
  </tr>
  <tr style="background-color: red;">
    <td>NAME</td><td>AGE</td>
  </tr>
  <tr style="background-color: red;">
    <td>NAME</td><td>AGE</td>
  </tr>
  

Answer №1

If you're interested in a CSS-only approach, here's a sample code snippet:

table tr:nth-of-type(n) {
  background: blue;
}

table tr:nth-of-type(8n),
table tr:nth-of-type(8n-1),
table tr:nth-of-type(8n-2),
table tr:nth-of-type(8n-3) {
  background: red;
}
<table>
  <tr>
    <td>NAME</td>
    <td>AGE</td>
  </tr>
  <tr>
    <td>NAME</td>
    <td>AGE</td>
  </tr>
  <tr>
    <td>NAME</td>
    <td>AGE</td>
  </tr>
  <tr>
    <td>NAME</td>
    <td>AGE</td>
  </tr>
  </table>

Answer №2

You have the option to utilize JS to gather all tr-elements and customize the background color of each row according to your preferences:

var trList = document.getElementsByTagName('tr');
var n = 0;
var color = 'pink';
for(var key in trList) {
var trElem = trList[key];
if( n > 3 ) {
  n = 0;
    color == 'pink' ? color = 'lightblue' : color = 'pink';
  }
  trElem.style.backgroundColor = color;
n++;
}
table { border-collapse:collapse; }
td { border: 1px solid #000; }
<table>
  <!--- odd -->
  <tr>
    <td>NAME</td><td>AGE</td>
  </tr>
  ...
  </tr>
</table>

https://jsfiddle.net/8cvpubto

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

Executing a C# program that sends a web request without using JavaScript

My goal is to programmatically download the contents of a website, but it seems like this content is being loaded through ajax calls. Interestingly, when I disable javascript in my browser, only one request is made by the page and all the content is displa ...

Steps for pulling data from the Google Analytics query tool

I'm looking to retrieve my Google Analytics report using an API and save it locally. I've set up a Report in Google Analytics Explore, see attached image: https://i.sstatic.net/lkbKj.jpg From there, I can download the CSV file containing the da ...

Enhancing Accessibility of the 'Return to Top' Link

Currently, I am designing a web page that requires users to scroll extensively. To enhance the user experience, I have included a back-to-top link at the bottom of the page for easy navigation back to the top. This is the HTML markup I have implemented: ...

SuperAgent - Refresh the initial request with a new bearer token upon encountering unauthorized access

Issue: I encountered a problem while attempting to resend my original request using superagent. Here is some pseudo code that I came up with: function retryRequest({ params }) { return superagent.post(url) .set("Authorization", `Bear ...

Guide to implementing CRUD operations on a remote MongoDB using Node.js

Recently, I delved into the world of NodeJS and discovered its server-side capabilities. My current project involves interacting with MongoDB on a remote server using the nodejs mongodb driver. With just a few lines of code, I am able to connect to the dat ...

Implementing server authentication with Faye in Node.js

As a complete newbie to node.js and faye, I'm struggling with the basics and not sure what questions to ask. This is how my faye server setup looks like, running on Nodejitsu: var http = require('http'), faye = require('faye' ...

What is the process for embedding a 3D model using three.js into a specific div on a webpage?

Lately, I've been struggling with a persistent issue. I can't seem to figure out how to integrate my three.js scene into a div on my website. Despite watching numerous YouTube videos and reading countless articles on the topic, I still haven&apos ...

Different Ways to Make Custom Checkboxes Overlap with Labels in CSS

Hello everyone, I am currently diving into the world of CSS and HTML. My goal right now is to create a custom checkbox with a list of options. During my research, I stumbled upon an example on how to create custom checkboxes at this link. However, when imp ...

Show validation error messages for radio buttons alongside images in a single row

Within a div, I have placed three radio buttons with images inline. My goal is to show a validation message using bootstrap when the submit button is clicked and there is no user input. I attempted to add another div after the radio buttons with the class ...

Dynamic reloading of a div with form data using jQuery's AJAX functionality

I am currently developing an online visitor chat software using PHP and MySQL. My goal is to load the page when the submit button is clicked. Submit Button ID: send Visitor ID: vid Chat ID: cid Below is the snippet of code for an Ajax request that I hav ...

CSS printing displays a blank bar in white color

Attempting to generate a ticket with the dimensions of 203mm x 82mm using HTML and CSS through Python (including cgi, jinja2, weasyprint). The template will be converted into a PDF for users to download via a button on the website. The HTML Body: <body ...

Retrieve a file from an Express API using React with the help of Axios

When working with a React client and an Express API, how can the React client download a file sent by the Express API? Issue: If I manually enter the URL into my browser's address bar and hit enter, the file downloads successfully. However, when I ...

Is there a way to alphabetically and numerically organize a table in vue.js?

Currently, I am implementing sorting functionality for a table using vue.js. While I have successfully achieved ascending sorting for numbers, I am facing challenges with getting the descending and alphabetical sorting to function properly. Below is the H ...

The error message "404 Not found" is returned when attempting to retrieve a Google spreadsheet

I have exhausted all of my options on the web trying to retrieve my Google spreadsheet as a json file. $.getJSON() However, I am constantly receiving a 404 Not Found error. When I publish to the web, the URL I get is: https://docs.google.com/spreadsheets ...

Error: Attempting to create a 'guid' property on the 'option:selected' string is not possible and results in a TypeError

Encountering an error when trying to implement cascading drop down functionality using Ajax. Can someone provide assistance? <script type="text/javascript"> $("#os").change(function () { debugger var osid = $(this).select("opt ...

Identify the absence of search results in an Ajax request to the search page before rendering the HTML content

I am attempting to retrieve JSON code from a page using the following PHP function: private function __ajax_admin_search($username = '') { $result = $this->admin_login->Admin_Username_Ajax($username); $count = count($result); for ...

How do I activate the <li> tag using jQuery?

I am currently implementing pagination on my webpage using the following JavaScript code: var pagingList = $('<ul>', {class: 'pagination list-unstyled list-inline'}); ...

The method request.getParameter in Servlet may sometimes result in a null

My website utilizes JQuery to make an Ajax call to a servlet. function sendAjax() { $.ajax({ url: "/AddOrUpdateServlet", type: 'POST', dataType: 'json', ...

What benefits are there to converting a jQuery application to Angular?

If I have a basic landing page with jQuery effects that I want to upgrade by "angularizing" it with AngularJS, how could I do so? For example, when using AngularJS for a contact form, it's known to be simple to implement. When considering DOM effects ...

Using the "i" parameter in a Lodash for loop results in undefined, however, it functions properly with specific values set

My goal is to use Lodash to search for specific integer values in an object and then store some of those values in an array. The integers are variable and come from a separate array, but I am consistently getting undefined as the result. If I manually inp ...