How to Change the Background Color of a Row in JavaScript

Written by steve mcdonnell Google
  • Share
  • Tweet
  • Share
  • Pin
  • Email
How to Change the Background Color of a Row in JavaScript
Using colour on a Web page can help highlight important buttons. (Hemera Technologies/Photos.com/Getty Images)

When displaying tabular data on a Web page using an HTML table, you might want to use colour to enhance the display or make the data in the table more legible. There are two ways to change the background colour of a row in an HTML table using JavaScript. The first method uses JavaScript by itself, and the second uses CSS and JavaScript.

Skill level:
Moderate

Other People Are Reading

Instructions

  1. 1

    Create a new HTML file using a text editor or Notepad. Enter an HTML skeleton and change the title as desired. For example, type:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml">

    <head>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Row Colors</title>

    </head>

    <body>

    </body>

    </html>

  2. 2

    Create an HTML table between the "body" tags. For example, type:

    <table id="myTable">

    <tr>

    <td>Tom</td><td>Male</td>

    </tr>

    <tr>

    <td>Susan</td><td>Female</td>

    </tr>

    </table>

  3. 3

    Get a pointer to the table element and get an array of pointers to each row in the table through their "tr" tags. Access the "backgroundColor" attribute directly to change it. For example, type:

    <script type="text/JavaScript">

    var table = document.getElementById("myTable");

    var rows = table.getElementsByTagName("tr");

    rows[0].style.backgroundColor = "#F30";

    rows[1].style.backgroundColor = "#09C";

    </script>

  4. 4

    Create a CSS style and place it between the "head" tags in the Web page. For example, type:

    <style type="text/css">

    .even { backgroundColor: #F30 }

    .odd { backgroundColor: #00C }

    </style>

  5. 5

    Write a JavaScript function that inserts the CSS class to change the background colour. For example, type:

    <script type="text/JavaScript">

    var table = document.getElementById("myTable");

    var rows = table.getElementsByTagName("tr");

    rows[0].className = "even";

    rows[1].className = "odd";

    </script>

Don't Miss

Filter:
  • All types
  • Articles
  • Slideshows
  • Videos
Sort:
  • Most relevant
  • Most popular
  • Most recent

No articles available

No slideshows available

No videos available

By using the eHow.co.uk site, you consent to the use of cookies. For more information, please see our Cookie policy.