Ralphonz
Ralphonz

Reputation: 693

Alternating Table Rows With Javascript issue

I have the following script working to add odd and even classes to alternating table rows which works fine.

function alternate(){ 
if(document.getElementsByTagName){  
var table = document.getElementsByTagName("table");
var rows = document.getElementsByTagName("tr");
    for(i = 0; i < rows.length; i++){
  //manipulate rows   
      if(i % 2 == 0){  
        rows[i].className = "even"; 
      }else{  
        rows[i].className = "odd"; 
      }
    }
  } 
}

However a problem arises when there is more than one table on a page. I need the counter to reset for each table on the page so the first row of each table always has the same class (i.e. odd). Currently the second table on the page will just carry on counting rows odd-even so it will start on a different class if the first table has an odd number of rows.

Can anyone help me change this code to achieve this?

Upvotes: 1

Views: 1716

Answers (3)

Šime Vidas
Šime Vidas

Reputation: 185923

Here you go:

function alternate() {
    var i, j, tables, rows;

    tables = document.getElementsByTagName( 'table' );

    for ( i = 0; i < tables.length; i += 1 ) {
        rows = tables[i].rows;

        for ( j = 0; j < rows.length; j += 1 ) {
            rows[j].className = j % 2 ? 'even' : 'odd';
        }
    }   
}

Live demo: http://jsfiddle.net/simevidas/w6rvd/


Alternative solution:

(Substituting the for iteration statements with forEach invocations makes the code more terse. Doesn't work in IE8 though :/.)

function alternate() {
    var tables = document.getElementsByTagName( 'table' );

    [].forEach.call( tables, function ( table ) {
        [].forEach.call( table.rows, function ( row, i ) {
            row.className = i % 2 ? 'even' : 'odd';
        });
    }); 
}

Live demo: http://jsfiddle.net/simevidas/w6rvd/1/

Upvotes: 5

david
david

Reputation: 4278

do this work, based on each table

 function alternate(){ 
 if(document.getElementsByTagName){  
var table = document.getElementsByTagName("table");

var rows = document.getElementsByTagName("tr");

for(var a = 0; a < table.length; a++){
{
   for(var i = 0; i < table[a].rows.length; i++){
  //manipulate rows   
  if(i % 2 == 0){  
    table[a].rows[i].className = "even"; 
     }else{  
     table[a].rows[i].className = "odd"; 
      }
    }

    }

  } }

}

Upvotes: 0

samura
samura

Reputation: 4395

You have to add a for for each table:

function alternate(){ 
  if(document.getElementsByTagName){  
    var table = document.getElementsByTagName("table");
    // each table
    for(a = 0; a < table.length; a++){
      var rows = table[a].getElementsByTagName("tr");
      for(i = 0; i < rows.length; i++){
        //manipulate rows   
        if(i % 2 == 0){  
          rows[i].className = "even"; 
        }else{  
          rows[i].className = "odd"; 
        }
      }
    }
  }
}

Upvotes: 2

Related Questions