Compare any changed data of HTML table among different rows
In a HTML table where have multiple rows of same data with some difference in any cell. Now you want to highlight that specific cell data which is changed only.
We can achieve this using JavaScript. Here’s a basic example of how you could implement this functionality:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Highlight Changed Data</title>
<style>
.changed {
background-color: yellow;
}
</style>
</head>
<body>
<table id="data-table">
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Initial Value 1</td>
<td>Initial Value 2</td>
<td>Initial Value 3</td>
</tr>
<tr>
<td>Changed Value 1</td>
<td>Changed Value 2</td>
<td>Changed Value 3</td>
</tr>
<!-- Add more rows as needed -->
</tbody>
</table>
<script>
window.onload = function () {
const table = document.getElementById('data-table');
const rows = table.getElementsByTagName('tr');
for (let i = rows.length - 1; i > 0; i--) {
const currentRow = rows[i];
const previousRow = rows[i - 1];
if (!previousRow) {
break; // Exit loop if no previous row (first row)
}
const currentCells = currentRow.getElementsByTagName('td');
const previousCells = previousRow.getElementsByTagName('td');
for (let j = 0; j < currentCells.length; j++) {
const currentCell = currentCells[j];
const previousCell = previousCells[j];
if (currentCell.textContent !== previousCell.textContent) {
currentCell.classList.add('changed');
}
}
}
};
</script>
</body>
</html>
- This code compares each cell of each row with the corresponding cell of the previous row.
- If the content of a cell is different from the content of the corresponding cell in the previous row, it adds a changed class to highlight the change.
Note: You can customise the appearance of the changed cells by modifying the CSS class .changed.