CSS nth-child селектор не работает для таблицы, созданной JS - PullRequest
0 голосов
/ 19 января 2020

У меня есть веб-страница, где содержимое таблицы происходит из Google Sheets. Я добавляю данные листов в таблицу, создавая элементы таблицы (tr, td) и добавляя их как дочерние, как показано ниже. Затем я пытаюсь применить CSS, чтобы раскрасить чередующиеся строки разными цветами. Оказывается, он раскрашивает только первый экземпляр выделения.

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";
}

Итак, причина в том, что когда я добавляю каждый элемент с appendChild() родная часть не обновляется? Что на самом деле происходит?

1 Ответ

1 голос
/ 19 января 2020

Вы должны сделать querySelectorAll вместо querySelector. Так как querySelector дает вам только один элемент. Итак, ваш код будет выглядеть так:

// 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";
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...