0

with the following code I generate a table populating it with the data taken from a json file:

$(function() {
      $.getJSON("Api/TabellaTempoMedio.php", function(data) {
        $.each(data, function(index, row) {
          $("#result").append("<tr>");

          $.each(row, function(index2, column) {
            $("#result").append("<td>" + column + "</td>");
          });

          $("#result").append("</tr>");
        });
      });
    });

This is the Html code:

<table>
    <thead>
        <tr>
          <th>Field1</th>
          <th>Field2</th>         
        </tr>
      </thead>

      <tbody id="result">
      </tbody>
</table>

but I cannot alternate the rows of the table with different colors. I tried this on CSS but it does not work:

tr:nth-child(odd)  { background-color: grey; }

how can I do?

Paol96
  • 23
  • 4
  • “*it does not work*” is not a useful problem statement. Edit your question to include a description of specifically *how* you know it’s not working (expected vs. actual behavior). It’s also next to impossible to say definitively why this didn’t work without seeing the HTML this code is operating against as a [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). – esqew Mar 25 '21 at 20:20
  • with that css code the rows do not alternate and nothing changes – Paol96 Mar 25 '21 at 20:22
  • Your append process is incorrect. When you append the row to the table and then append a cell to the table the cell does not get inserted in the row. You can't insert closing tags as if you are writing html in a code editor. The DOM only understands full elements – charlietfl Mar 25 '21 at 21:11

1 Answers1

-1

.table-1{
  background: red;
}

.table-1 tr{
  background: blue;
}

.table-1 tr:nth-child(2n + 1){
  background: yellow;
}
<table class="table-1">
    <tr>
        <td>Data...</td>
    </tr>
    <tr>
        <td>Data...</td>
    </tr>
    <tr>
        <td>Data...</td>
    </tr>
    <tr>
        <td>Data...</td>
    </tr>
</table>
Dharman
  • 30,962
  • 25
  • 85
  • 135
Rajan Benipuri
  • 1,772
  • 1
  • 9
  • 21