Harvard Extension School
CSCI E-12 Fundamentals of Web Site Development | Spring 2019

## Things will go wrong...the Javascript Console is your friend

- United States Senate Table - Plain
- United States Senate Table - Striped with JS
- United States Senate Table - Striped with JS and Console Messages

    function stripeTable(tableid) {
      var mytable = document.getElementById(tableid);
      console.log("mytable is:");
      console.log(mytable);
      // get tbody (i.e. we dont' want to stripe the thead)
      var mytbody = mytable.getElementsByTagName('tbody');
      console.log("mytbody is:");
      console.log(mytbody);
      /*   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');
      console.log("myrows is:");
      console.log(myrows);
      console.log("myrows length is: " + myrows.length);

      /*  Iterate over the node list of "tr" returned, setting
          the class appropriately
        */
      for(var i=0; i<myrows.length; i++) {
          var senatorname = myrows[i].getElementsByTagName('td')[0].firstChild.nodeValue;
          console.log(senatorname);
        if ((i + 1) % 2 == 0) {
          // even rows
          console.log("row with index of " + i + " is evenRow");
          myrows[i].setAttribute('class','evenRow');
        } else {
          // odd rows
          console.log("row with index of " + i + " is oddRow");
          myrows[i].setAttribute('class','oddRow');
        }
      }
    }

`console.log()` allows you output messages to a console.

Copyright © David Heitmeyer