Search code examples
javascriptbackground-coloralternate

How to set alternate row background color using javascript


I am new to ASP.Net. I want to set the HTML table alternate row background color using javascript. How can I start with it.If I do like this,

<tr  id="230552" onClick="HighLightTR(230552);"><td>My Text Here</td></tr>  


   function HighLightTR (grpid) {  
   document.getElementById(grpid).style.background = '#3875D7';         
}  

it will apply only for that perticuler row. I want to apply two colors for alternate rows.


Solution

  • you can do it this way

    var rowCount=0;
    $('#tbl tr').each(function () {  
    
     if(rowCount%2==0){
      //document.getElementById(grpid).style.background = '#3875D7';  
      $(this).css(background,'#3875D7');       
     }else
     {
     //document.getElementById(grpid).style.background = '#3875D9';  
     $(this).css(background,'#3875D9');              
     }
     rowCount++;
    
    });  
    

    EDITED: Code has been converted to pure jQuery standard

    happy Coding :)