Harvard Extension School, Fall 2018
CSCI E-12 Fundamentals of Web Site Development

## Table striping with Javascript

- United States Senate Table - Plain
- United States Senate Table - Striped with JS

- Use `onload` event attribute of `body` element to call striping function.
- Will use Document Object Model to access parts of the page
- Basic flow:
  - Get the table to stripe (`getElementById`)
  - Get the table body (`getElementsByTagName`)
  - Get the rows within the table body (`getElementsByTagName`)
  - Go through each row, and assign an "evenRow" or "oddRow" class attribute
    (`for` loop and `setAttribute` DOM method)

    function stripeTable(tableid) {
      var mytable = document.getElementById(tableid);
      // get tbody (i.e. we do not want to stripe the thead)
      var mytbody = mytable.getElementsByTagName('tbody');
      /*   getElementsByTagName gives us a Node List, so we need
         to access it as a list (Array), arrayname[i].
         Find all the tr within the tbody
      */
      var myrows =  mytbody[0].getElementsByTagName('tr');
      /*  Iterate over the node list of "tr" returned, setting
          the class appropriately
        */
      for(var i=0; i<myrows.length; i++) {
        if ((i + 1) % 2 == 0) {
          // even row -- the "%" operator is the "modulus" or remainder
          myrows[i].setAttribute('class','evenRow');
        } else {
          // odd row
          myrows[i].setAttribute('class','oddRow');
        }
      }
    }

Copyright © David Heitmeyer