Adriano_Pinaffo
Adriano_Pinaffo

Reputation: 1699

CSS nth-child selector not working for table created by JS

I have a web page where the content of the table comes from Google Sheets. I add the sheets data into the table by creating the table elements (tr, td) and and appending them as child as below. Then I try to apply CSS to colorize alternate rows with different colors. It turns out it only colorize the first instance of the selection.

HTML

<table id="list">
 <thead></thead>
 <tbody></tbody>
</table>

JS

document.addEventListener('DOMContentLoaded', function() {
  google.script.run.withSuccessHandler(makeList).getList();
});

// my Google Sheet data is in the "data" parameter below
function makeList(data) {
  console.log(data[0]);

  // Add Header
  var tbHead = document.querySelector('#list thead');
  var tr = document.createElement('tr');

  data[0].map(function(h) {
    var th = document.createElement('th');
    th.textContent = h;
    tr.appendChild(th);
    tbHead.appendChild(tr);
  });

  data.splice(0,1);
  console.log(data[0]);

  // Add rows
  var tbBody = document.querySelector('#list tbody');

  data.map(function(r) {
    var tr = document.createElement('tr');
    r.map(function(d) {
      var td = document.createElement('td');
      td.textContent = d;
      tr.appendChild(td);
      tbBody.appendChild(tr);
    });
  });

  // At this point the table is filled correcty (at leat visually)

  // Styling table
  configureTable();
}

// JS to change CSS of Table
function configureTable() {

  // The selection below selects only the second element of the table body, and not all of the even elements, the same happens if I select 2n.
  var tbEvenRow = document.querySelector("#list tbody tr:nth-child(even)");
  tbEvenRow.style.backgroundColor = "cyan";
}

So, is it the reason that when I added each element with appendChild() the sibling part is not updated? What is really going on?

Upvotes: 0

Views: 1310

Answers (1)

Nipun Jain
Nipun Jain

Reputation: 1014

You should do querySelectorAll instead of querySelector. As querySelector gives you only one element. So your code will look like this:

// JS to change CSS of Table
function configureTable() {

  // The selection below selects only the second element of the table body, and not all of the even elements, the same happens if I select 2n.
  var tbEvenRows = document.querySelectorAll("#list tbody tr:nth-child(even)");
  for ( let i = 0; i < tbEvenRows.length; i++) {

   tbEvenRoww[i].style.backgroundColor = "cyan";
  }
}

Upvotes: 1

Related Questions