1. Technology

JavaScript By Example

DOM Table: 5. Tbodies and Rows

By

Businesswoman working at desk
Blend Images/Ariel Skelley/Vetta/Getty Images

The tBodies, rows, and tBodies[0].rows methods are all nodelists since a table can have more than one tbody and more than one row. The difference between rows and tBodies[0].rows is that the first of these nodelists contains all of the rows in the table including the thead and tfoot while tBodies[0].rows only references the rows in the first tbody. Also since there can be more than one of each the corresponding add and delete methods require that you identify which tbody or row or row within a specified tbody that you are adding or deleting by passing it in as a parameter.

In this example we are going to add a class to the alternate rows within each tbody to allow those rows to be styled differently. Since we are using the available table references the code ends up shorter and easier to read than if we were using getElementsByTagName and in this particular case (since I actually tested it) the code runs faster than the more generic alternative in most browsers (five times as fast in Opera).


var tables, bodies, rows;
tables = document.getElementsByTagName('table');
for (var i=tables.length-1; i >= 0; i--) {
  bodies = tables[i].tBodies;
  for (var j=bodies.length-1; j >= 0; j--) {
    rows = bodies[j].rows;
    for (var k = 1, kk = rows.length; k < kk; k+=2) {
    rows[k].className += ' alt';
    }
  }
}

Reader Submissions: Help Others By Providing Your Own JavaScript Examples

JavaScript By Example
  1. About.com
  2. Technology
  3. JavaScript
  4. Javascript Tutorials
  5. JavaScript By Example
  6. Document Object Model
  7. JavaScript By Example - DOM Table: Tbodies and Rows

©2014 About.com. All rights reserved.