Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternate row colors in javascript

Tags:

javascript

I'm making a table which have alternate row colors, for example the first row is red, the second is green, the third is red and so on. Written this code so far and got stuck, don't know what to put in if statement.

var color = "red";
var outputString = "<table border=1 width=50%>"; 
outputString = outputString + "<tr><td>a</td><td>a^2</td><td>a^3</td></tr>";    
for (var i = 1; i <= 5; i++ ) {
if (i%2 == 0) {

} else {

}
outputString += "<tr class=" + color + ">" + "<td>" + i + "</td>" + "<td>" + i * i + "</td>" + "<td>" + i * i * i + "</td>" + "</tr>";
    } 
outputString += "</table>"; 
document.write(outputString);
like image 765
user2526749 Avatar asked May 30 '26 05:05

user2526749


1 Answers

Here is the pure css version,

table tr:nth-child(odd) td{
}
table tr:nth-child(even) td{
}

And here is the jQuery solution for the same,

$(function(){
   $("table tr:even").addClass("evenClassName");
   $("table tr:odd").addClass("oddClassName");
});

Here is the pure JavaScript solution,

function altrows(firstcolor,secondcolor)
{
    var tableElements = document.getElementsByTagName("table") ;
    for(var j = 0; j < tableElements.length; j++)
    {
        var table = tableElements[j] ;

        var rows = table.getElementsByTagName("tr") ;
        for(var i = 0; i <= rows.length; i++)
        {
            if(i%2==0){
                rows[i].style.backgroundColor = firstcolor ;
            }
            else{
                rows[i].style.backgroundColor = secondcolor ;
            }
        }
    }
}
like image 154
Chamika Sandamal Avatar answered Jun 01 '26 19:06

Chamika Sandamal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!