Skip to content

Instantly share code, notes, and snippets.

@rostrovsky
Last active November 9, 2023 23:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rostrovsky/d707c2160049d517677c9ff85c5a27ba to your computer and use it in GitHub Desktop.
Save rostrovsky/d707c2160049d517677c9ff85c5a27ba to your computer and use it in GitHub Desktop.
Automatic rowspan in the table
function autoRowSpan(tableId) {
var table = document.getElementById(tableId);
var rows = table.rows;
// Iterate through each column
for (var colIndex = 0; colIndex < rows[0].cells.length; colIndex++) {
var prevCell = null;
var prevCellText = '';
var rowspan = 1;
// Iterate through each row
for (var rowIndex = 0; rowIndex < rows.length; rowIndex++) {
var cell = rows[rowIndex].cells[colIndex];
if (prevCell && cell.innerText === prevCellText) {
// If this cell is the same as the previous one, hide it and increase rowspan
cell.style.display = 'none';
rowspan++;
prevCell.rowSpan = rowspan;
} else {
// New cell content found, reset counters
if (prevCell && rowspan > 1) {
prevCell.rowSpan = rowspan;
}
prevCell = cell;
prevCellText = cell.innerText;
rowspan = 1;
}
}
// Ensure the last cell in the column gets its rowspan set
if (prevCell && rowspan > 1) {
prevCell.rowSpan = rowspan;
}
}
}
// Call the function with your table id
autoRowSpan('myTable');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment