search
HomeWeb Front-endJS TutorialAlter Table Row Background Colors Using JavaScript

Alter Table Row Background Colors Using JavaScript

Key Takeaways

  • JavaScript can be used to dynamically alter table row background colors, enhancing readability without needing to hardcode every second row or regenerate the HTML page from a server application.
  • One method involves defining two classes for background colors in a style element, then using JavaScript to assign these classes to odd and even rows respectively.
  • A more complex method allows for multiple alternating colors by using an array that holds all these colors and assigning them to rows based on their index.
  • A final method calculates the color depending on the number of rows in the table, the start color and a given factor, creating a gradient effect. This method requires careful consideration of color combinations to maintain readability.

Many sites that present tabular data use alternating background colors to increase the readability of that data. And as I developed a site, I realised I wanted to do that, too. The problem? In my case the table was not generated by a server side application or script of which you can find numerous examples on the Web.

The obvious solution was to hardcode every second row to ensure it had a different background color. But I wanted the table to be dynamic, so that it was possible to add a new row in the middle of the table without changing the background color attribute of the rows that followed.

My solution uses JavaScript, as CSS3 isn’t truly a viable option yet. Browsers today still struggle to support CSS1 and CSS2. Even though HTML tables aren’t recommended for Web page layout, they are still perfectly suited to the presentation of tabular data. In this tutorial, I’ll present three examples based on the same idea. I have tested the solutions in IE6, Firefox 1.0, Mozilla 1.7.3 and Opera 7.54 on the Windows platform only.

Getting Started

Let’s start with an ordinary html table. Whether the table contains head/foot elements doesn’t matter in this case:





 
 
       
0 - some txt
1 - some txt
2 - some txt
3 - some txt
4 - some txt

Now, we need to check that the browser is fairly new and has the necessary JavaScript capabilities (i.e. W3C DOM support). The following line performs this check, disqualifying Netscape 4 and others of that generation. Such browsers will make no attempt to color the table.

if(document.getElementById)

Also note that common to all these examples is this code:

var table = document.getElementById(id);   <br>
var rows = table.getElementsByTagName("tr");   <br>
for(i = 0; i 
    //manipulate rows <br>
      ...
Example 1

This first example uses a style element through which we have defined two classes for background colors:

<style> <br>
  .odd{background-color: white;} <br>
  .even{background-color: gray;} <br>
</style>

The style is flexible: it could just as well define something else, such as that every second row should display in italics. The complete function looks like this:

function alternate(id){ <br>
  if(document.getElementsByTagName){  <br>
    var table = document.getElementById(id);   <br>
    var rows = table.getElementsByTagName("tr");   <br>
    for(i = 0; i 
  //manipulate rows <br>
      if(i % 2 == 0){ <br>
        rows[i].className = "even"; <br>
      }else{ <br>
        rows[i].className = "odd"; <br>
      }       <br>
    } <br>
  } <br>
}

Here, %, the modulo operator, gives us the remainder in division.

The above function should be called from the onload event of the body tag:





 
 
       
0 - some txt
1 - some txt
2 - some txt
3 - some txt
4 - some txt

The result could look something like this:

Alter Table Row Background Colors Using JavaScript

Example 2

Let’s move on to the next example — something a little more adventurous. Instead of using just two alternating colors, I want to use several. Let’s add an array that holds all these colors.

Since a limited number of colors have a defined name in HTML, we’ll switch to hexadecimal values. The resulting colors will be made up of three values: red, green, and blue. White is achieved when all three colors are turned on at max: #ffffff. The opposite, black, is #000000.

if(document.getElementById)

The row-manipulating code will comprise just a single line, but instead of copying and pasting the same code, we’ll make a separate function call:

var table = document.getElementById(id);   <br>
var rows = table.getElementsByTagName("tr");   <br>
for(i = 0; i 
    //manipulate rows <br>
      ...

Here, I’ve also added a function for Example 1 called doAlternate. This makes it easier to switch between the different methods by which we can alternate the table’s row colors.

As seen in the above fragments, it’s possible to set for the rows the CSS class name, or a specific attribute of an HTML tag:

<style> <br>
  .odd{background-color: white;} <br>
  .even{background-color: gray;} <br>
</style>

The result of Example 2 might appear as shown below:

Alter Table Row Background Colors Using JavaScript

Example 3

The final example shows a really colorful variant in which the color is calculated depending on the number of rows in the table, the start color and a given factor.

First, we need to set a few variables:

function alternate(id){ <br>
  if(document.getElementsByTagName){  <br>
    var table = document.getElementById(id);   <br>
    var rows = table.getElementsByTagName("tr");   <br>
    for(i = 0; i 
  //manipulate rows <br>
      if(i % 2 == 0){ <br>
        rows[i].className = "even"; <br>
      }else{ <br>
        rows[i].className = "odd"; <br>
      }       <br>
    } <br>
  } <br>
}

We now add a new function, doGradient.

 <br>
... <br>
 <br>


...

...

Since the colors are being calculated, we need to make sure that we don’t go out of range, Valid values are from 0 to 255. The color argument is not separated into RGB values, so we need to pad if we go below 16, otherwise, the value will be illegal. If we have a really long table or a big steps value, the gradient will turn in the other direction. In this function, the blue part is fixed and the other two are modified.

The toString method is quite handy when you need to convert numbers — decimal to hex, in this case. The argument in toString is the radix, ie. 2 for binary, 10 for decimal, and 16 for hex. The image below shows how the table appears in Results in Firefox 1.0, IE6, Mozilla 1.7 and Opera 7.5.

Alter Table Row Background Colors Using JavaScript

Take care not to make the display too colorful — we still want to ensure the readability of our tabular data. With some color combinations, it might even be necessary to change the color of the table text using something like this:





 
 
       
0 - some txt
1 - some txt
2 - some txt
3 - some txt
4 - some txt
Conclusion

Using CSS and JavaScript, it’s fairly easy to add or increase the readability of our code without having to regenerate the HTML page from a server application. As we’ve seen here, it can also be added on static HTML pages. To see these examples in action, download the HTML file containing the code.

Frequently Asked Questions (FAQs) about Changing Background Colors in JavaScript

How can I change the background color of a specific row in a table using JavaScript?

To change the background color of a specific row in a table, you can use the JavaScript method getElementById or querySelector to select the row, and then change its style property. Here’s an example:

document.getElementById("myRow").style.backgroundColor = "red";
// or
document.querySelector("#myRow").style.backgroundColor = "red";
In this example, “myRow” is the id of the row you want to change. You can replace “red” with any valid color name or color code.

Can I change the background color of multiple rows at once?

Yes, you can change the background color of multiple rows at once using JavaScript. You can use the querySelectorAll method to select all the rows you want to change, and then use a loop to change the background color of each row. Here’s an example:

var rows = document.querySelectorAll(".myRows");
for (var i = 0; i rows[i].style.backgroundColor = "blue";
}
In this example, “myRows” is the class of the rows you want to change. You can replace “blue” with any valid color name or color code.

How can I change the background color of a row when I click on it?

To change the background color of a row when you click on it, you can use the onclick event in JavaScript. Here’s an example:

document.getElementById("myRow").onclick = function() {
this.style.backgroundColor = "green";
}
In this example, “myRow” is the id of the row you want to change. You can replace “green” with any valid color name or color code.

Can I change the background color of a row based on its content?

Yes, you can change the background color of a row based on its content using JavaScript. You can use the innerHTML property to get the content of the row, and then use an if statement to change the background color based on the content. Here’s an example:

var row = document.getElementById("myRow");
if (row.innerHTML.includes("Important")) {
row.style.backgroundColor = "yellow";
}
In this example, “myRow” is the id of the row you want to change, and “Important” is the content you are looking for. You can replace “yellow” with any valid color name or color code.

How can I change the background color of a row when I hover over it?

To change the background color of a row when you hover over it, you can use the :hover pseudo-class in CSS. Here’s an example:

#myRow:hover {
background-color: pink;
}
In this example, “myRow” is the id of the row you want to change. You can replace “pink” with any valid color name or color code.

Can I change the background color of a row back to its original color?

Yes, you can change the background color of a row back to its original color using JavaScript. You can store the original color in a variable before you change it, and then use this variable to change the color back. Here’s an example:

var row = document.getElementById("myRow");
var originalColor = row.style.backgroundColor;
row.style.backgroundColor = "purple";
// To change the color back:
row.style.backgroundColor = originalColor;
In this example, “myRow” is the id of the row you want to change. You can replace “purple” with any valid color name or color code.

How can I change the background color of a row every few seconds?

To change the background color of a row every few seconds, you can use the setInterval function in JavaScript. Here’s an example:

var row = document.getElementById("myRow");
setInterval(function() {
row.style.backgroundColor = getRandomColor();
}, 2000);
In this example, “myRow” is the id of the row you want to change, and getRandomColor is a function that returns a random color. The number 2000 is the interval in milliseconds (2000 milliseconds = 2 seconds).

Can I change the background color of a row based on a condition?

Yes, you can change the background color of a row based on a condition using JavaScript. You can use an if statement to check the condition, and then change the background color if the condition is true. Here’s an example:

var row = document.getElementById("myRow");
if (someCondition) {
row.style.backgroundColor = "orange";
}
In this example, “myRow” is the id of the row you want to change, and someCondition is the condition you want to check. You can replace “orange” with any valid color name or color code.

How can I change the background color of a row when I select it?

To change the background color of a row when you select it, you can use the onselect event in JavaScript. However, this event is not commonly used for table rows, because it’s usually used for text input fields. A more common approach is to change the background color when you click on the row, as explained in question 3.

Can I change the background color of a row in a specific column?

Yes, you can change the background color of a row in a specific column using JavaScript. You can use the cellIndex property to get the index of the column, and then change the background color of the row if the index matches the specific column. Here’s an example:

var row = document.getElementById("myRow");
if (row.cells[0].cellIndex == specificColumn) {
row.style.backgroundColor = "teal";
}
In this example, “myRow” is the id of the row you want to change, and specificColumn is the index of the specific column. You can replace “teal” with any valid color name or color code.

The above is the detailed content of Alter Table Row Background Colors Using JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function