How to color cells in a table with Javascript?

0

I've done the table code, but I do not know how to color the columns.

<script>
    window.onload = function tabela(){  

    var lin = prompt("linha");
    lin = parseInt(lin);
    var col = prompt("coluna");
    col = parseInt(col);

    var conteudo = "<table border = 0>";

        for (i=1;i<=lin;i++){

            conteudo += "<tr>";

                for (j=1;j<=col;j++){

                    conteudo += "<td>" + (i+","+j)+"</td>"

                }

            conteudo += "</tr>";
        }

    conteudo += "</table>"; 
    document.getElementById("tab").innerHTML = conteudo;

</script>
</head>

<body>

    <div id="tab"></div>

</body>
</html>
    
asked by anonymous 22.09.2016 / 23:36

1 answer

2

You can use CSS to do this:

td:nth-child(odd){
    background-color: yellow;
}
td:nth-child(even){
    background-color: green;
}

jsFiddle: link

If you really want to use JavaScript you can do so in the internal loop:

for (j = 1; j <= col; j++) {
    var cor = (j % 2 == 0) ? 'green' : 'yellow';
    conteudo += "<td style=\"background-color:" + cor + ";\">" + (i + "," + j) + "</td>"
}

jsFiddle: link

    
22.09.2016 / 23:39