Stripe Table Rows DOM JS Function

/ Published in: JavaScript
Save to your folder(s)

This function looks for tables in a web page, then loops through the rows and sets the backgroundColor for ever other row.This creates a striped table which is easier to read.

Copy this code and paste it in your HTML
  1. function stripeTables() {
  2. if(!document.getElementsByTagName) return false;//basic old browser check
  3. var tables = document.getElementsByTagName("table");//grab the tables in the document
  4. for(i=0; i<table.length; i++) {//loop through the tables
  5. var odd = false;//creat an odd function for the table, set it to false
  6. var rows = tables[i].getElementsByTagName("tr");//grab the rows in the specific table
  7. for(j=0; j<rows.length; j++) {//loop through the rows in the specific table
  8. if(odd == true) {
  9. rows[j].style.backgroundColor = "#ffc";//if odd is true, set the bg color to this
  10. odd = false;//set odd to false
  11. } else {
  12. odd = true;//set odd to true, this is picked up by next iteration and styles the next row
  13. }
  14. }
  15. }
  16. }

Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.