Skip to content

Instantly share code, notes, and snippets.

@wernersbacher
Created December 13, 2022 18:58
Show Gist options
  • Save wernersbacher/c4ba711d5911cb29d7465cc25b7317f9 to your computer and use it in GitHub Desktop.
Save wernersbacher/c4ba711d5911cb29d7465cc25b7317f9 to your computer and use it in GitHub Desktop.
Resolve a HTML table's rowspan attributes (table normalizing) in Javascript
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
<script>
function normalize(tagname){
var newTable = $(tagname).clone(true);
$(tagname).empty();
$(newTable.children()).children().each(function(column_index, row_raw){
var currentRow = $(row_raw);
currentRow.children().each(function(row_index, cell_raw){
current_cell = $(cell_raw);
var rowspan_num = current_cell.attr("rowspan");
if(rowspan_num < 2)
return; // do nothing, everything ok (bascially a "continue" statement)
var nextRow = currentRow.next();
for (let i =0; i < rowspan_num-1; i++) {
// creating rowspan_num-1 elements
// copy the cell
var item_new = current_cell.clone(true);
// Remove rowspans attributes
current_cell.removeAttr("rowspan");
item_new.removeAttr("rowspan");
// last item's index in next row
var indexOfLastElement = nextRow.children().length-1;
// append if current index is bigger, if not, insert in middle of next row
if(row_index > indexOfLastElement)
nextRow.append(item_new); // appending at the end of next row
else
item_new.insertBefore(nextRow.children().eq(row_index)); // intermediate cell insertion
// get the next row; if we are finished, this doesnt matter anymore
nextRow = nextRow.next();
}
});
$(tagname).append(currentRow);
});
}
</script>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<table id="tbl1">
<tr>
<th>Month</th>
<th>Savings</th>
<th>Savings for holiday!</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
<td rowspan="3">$50</td>
</tr>
<tr>
<td>February</td>
<td rowspan="2">$80</td>
</tr>
<tr>
<td>February</td>
</tr>
</table>
<button id="normalize">Normalize Table</button>
<script>
// onclick button handler, only for demo
$("#normalize").click(function(){
normalize("#tbl1")
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment