[FIXED] Display different backgrounds for alternating rows of expanding table

Issue

I am using primeNg row expansion feature.
Code is here : https://primefaces.org/primeng/showcase/#/table/rowexpansion

I have a requirement to display yellow background for odd rows and grey background for even rows, but the additional inserted row having the child table should not be included during calculation.

Consider the below html example, where user has expanded the first row. I do not want the rows with ‘table-row-expand’ class to be considered in the even/odd rule. Here I want first row to have yellow color, second row to have grey color and third row to have yellow again. The expanded row should not have any background.

Note that the .table-row-expand row gets added to the DOM only when user expands the corresponding row. Kindly help me with this problem.

.table-row:nth-child(odd) {
  background-color: yellow;
}

.table-row:nth-child(even) {
  background-color: grey;
}
<table>
  <tr class='header-row'>
    <th> </th>
  </tr>
  <tr class='table-row'>
    <td> // first row (should be gray)</td>
  </tr>
  <tr class='table-row-expand'>
    <td> // expanded row (should not be colored)
      <div>
        <p-table> // child table </p-table>
      </div>
    </td>
  </tr>
  <tr class='table-row'>
    <td> // second row (should be yellow)</td>
  </tr>
  <tr class='table-row'>
    <td> // third row (should be gray)</td>
  </tr>
</table>

Solution

Save yourself a headache and drop in a wee bit ‘o JavaScript. You may need to put this code in a function to be called when new rows are added.

.table-row.odd {
  background-color: yellow;
}

.table-row.even {
  background-color: grey;
}
<table>
  <tr class='header-row'>
    <th> </th>
  </tr>
  <tr class='table-row'>
    <td> // first row (should be gray)</td>
  </tr>
  <tr class='table-row-expand'>
    <td> // expanded row (should not be colored)
      <div>
        <p-table> // child table </p-table>
      </div>
    </td>
  </tr>
  <tr class='table-row'>
    <td> // second row (should be yellow)</td>
  </tr>
  <tr class='table-row'>
    <td> // third row (should be gray)</td>
  </tr>
</table>

<script>
  const styledRows = document.querySelectorAll('.table-row');
  const isOdd = n => Boolean(n % 2); // returns true if n / 2 has a remainder

  styledRows.forEach((row, i) => {
    row.classList.add(isOdd(i) ? 'odd' : 'even');
  });
</script>

Answered By – isherwood

Answer Checked By – Robin (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published