1

Есть таблица с месяцами и цифровыми значениями. Там, где цифровое значение меньше 100 на всю строку, надо добавить CSS класс ".attention". Я делаю перебор массива, но не могу присвоить CSS.

<style>
  .attention {
    background-color: lightcoral;
    color: white;
  }
</style>
</head>

<body>
  <table id="statsTable">
    <tr>
      <td>Январь</td>
      <td>20</td>
    </tr>
    <tr>
      <td>Февраль</td>
      <td>140</td>
    </tr>
    <tr>
      <td>Март</td>
      <td>115</td>
    </tr>
    <tr>
      <td>Апрель</td>
      <td>100</td>
    </tr>
    <tr>
      <td>Март</td>
      <td>80</td>
    </tr>
    <tr>
      <td>Июнь</td>
      <td>90</td>
    </tr>
    <tr>
      <td>Июль</td>
      <td>100</td>
    </tr>
  </table>

  <script>
    /* <----START--------> */

    const table = document.getElementById('statsTable');
    let tableRows = table.getElementsByTagName('tr');
    let index = 0;

    while (index < tableRows.length) {
      if (tableRows[index].getElementsByTagName('td')[1].innerText < 100) {
        tableRows[index].classList.add('attention');
        tableRows = table.getElementsByTagName('tr');
      } else {
        index++;
      }
    }
    /* <-----END---------> */
  </script>

2
  • 1
    else уберите, просто оставьте index++ после секции if 9 дек 2021 в 12:21
  • 1
    иначе у вас бесконечный цикл происходит, потому что индекс не увеличивается, и все время обрабатывается первая ячейка 9 дек 2021 в 12:30

1 ответ 1

0

Помогло так:

/* <----START--------> */

    const table = document.getElementById('statsTable');
    let tableRows = table.getElementsByTagName('tr');
    let index = 0;

    while (index < tableRows.length) {
      if (tableRows[index].getElementsByTagName('td')[1].innerText < 100) {
        tableRows[index].classList.add('attention');
        tableRows = table.getElementsByTagName('tr');
      } 
        
      index++;
    }
    /* <-----END---------> */

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.