0

I found a script to change the color of every seccond row to make it look nice, but when i add another table on the same page it colours the first table but the seccond table gets no colour why is this??

code of table.js

jQuery(document).ready(function() {

    //for tables style
    function altRows(id){
    if(document.getElementsByTagName){  

        var table = document.getElementById(id);  
        var rows = table.getElementsByTagName("tr"); 

        for(i = 0; i < rows.length; i++){          
            if(i % 2 == 0){
                rows[i].className = "evenrowcolor";
            }else{
                rows[i].className = "oddrowcolor";
            }      
        }
    }
}
window.onload=function(){
    altRows('alternatecolor');
}



});

php webpage code:

  <?php 
//first table
       echo'
           <table class="altrowstable" id="alternatecolor">
      <tr>
      <th>Seller</th>
      <th>price(per 1k doge)</th>
      <th>payment allowed</th>
      <th>View Trade</th>
      </tr>

      <td>Example</td>
        <td>Example</td>
          <td>Example</td>
        </tr>';



     echo'</table> <br />';  


//seccond table
 echo  '<h3>trades on going </h3>';

    echo ' <table class="gridtable">
     <table class="altrowstable" id="alternatecolor">
        <tr>
        <th>Trade User</th>
        <th>Cost($)</th>
        </tr>

     <td>Example</td>
        <td>Example</td>
          <td>Example</td>
        </tr>';

     echo'</table> ';  

?>
1
  • 1
    dont do it by id. do it by class Commented Apr 2, 2014 at 15:20

2 Answers 2

3

A better way to do this is via CSS.

tr:nth-child(odd) { background-color: black, color: white }
tr:nth-child(even) { background color: white, color: black }

This will apply to all tables on your page, without having to mess about with the HTML as output by your PHP or Javascript.

Sign up to request clarification or add additional context in comments.

Comments

0

You are referencing the first table by its id alternatecolor when you call document.getElementById(id). Perhaps add an id to your second table, then call altRows again for it?

Editing the second table in the PHP File:

echo ' <table class="gridtable" id="secondTable">

Editing the JavaScript:

window.onload=function(){
    altRows('alternatecolor');
    altRows('secondTable');
}

1 Comment

coudent figuar out how to do it and your way just fixed it for me thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.