How to Change the Background Color of a Row in JavaScript
When displaying tabular data on a Web page using an HTML table, you might want to use color to enhance the display or make the data in the table more legible. There are two ways to change the background color of a row in an HTML table using JavaScript. The first method uses JavaScript by itself, and the second uses CSS and JavaScript.
Instructions
-
-
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
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
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
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
Write a JavaScript function that inserts the CSS class to change the background color. 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>
-
1
References
- Photo Credit Hemera Technologies/Photos.com/Getty Images