How to color cells from a table with Javascript?

Asked

Viewed 685 times

0

I’ve done the table code, but I don’t 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>
  • 1

    I’ve formatted your code, but you need to fix the indentation and see if you’re missing one } at the end. Please review the code if possible. I took a few blank lines just to avoid the need to scroll while reading your code. To change/fix, just click on [Edit].

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: https://jsfiddle.net/07q0dub2/

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: https://jsfiddle.net/07q0dub2/2/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.