How do I change the style of a cell in a column in an HTML table based on conditions?

291 Views Asked by At

I have an HTML table where the rows and cells are created dynamically using JavaScript. I need to change the style (background colour) of the cell with the lowest and highest value within each column. How do I achieve this? I have given each <td> tag within the same column a class.

<table id="table">
    <thead id="thead">
        <th>col1</th>
        <th>col2</th>
        <th>col3</th>
        <th>col4</th>
        <th>col5</th>
        <th>col6</th>
    </thead>
    <tbody id="tbody">

        //DYNAMICALLY ADDED TR AND TDS ADDED HERE

    </tbody>
</table>
1

There are 1 best solutions below

0
Grizou On

In order to have all the children of one of your columns you can use the Element.children property. After you can iterate on this collection to get the value of each child and then compare each value to determine the maximum and the minimum value.

const myElement = document.getElementById('thead');
for (const column of myElement.children) {
  var maximum = 0;
  var maximumElement;
  var minimum = 0;
  var minimumElement;
  for (const cell of column.children) {
    if (cell.value > maximum)
      maximumElement = cell;
    if (cell.value < minimum)
      minimumelement = cell;
  }
  maximumElement.style.backgroundcolor = 'green';
  minimumElement.style.backgroundcolor = 'red';
}

I hope it's can help you