I’ve been trying to modify a html using JS table but keep failing. I want to take a simple table, slice it into columns and make a long one column table made out of each column of the original table. Here is a basic table:
For now I succeded only to slice it rowwise:
But my goal is to make it look like:
Column 1
Data 1
Data 4
Data 7
Column 2
…and so on.
(Vertically)
Here is the code:
<!DOCTYPE html>
<html>
<head>
<title>Transform Table</title>
<style>
/* Hide the transformed table by default */
table, th, td {
border: 1px solid black;
}
</style>
<script>
window.onload = function () {
transformTable();
};
function transformTable() {
var originalTable = document.getElementById("originalTable");
var transformedTable = document.getElementById("transformedTable");
for (var i = 0; i < originalTable.rows.length; i++) {
var row = originalTable.rows[i];
for (var j = 0; j < row.cells.length; j++) {
var cell = row.cells[j];
var newRow = transformedTable.insertRow();
var newCell = newRow.insertCell();
// Clone attributes from original cell to the new cell
for (var k = 0; k < cell.attributes.length; k++) {
var attr = cell.attributes[k];
newCell.setAttribute(attr.name, attr.value);
}
// Clone nested elements
var cellContents = cell.cloneNode(true);
// Remove the cloned <td> element and append its children
while (cellContents.firstChild) {
newCell.appendChild(cellContents.removeChild(cellContents.firstChild));
}
}
}
}
</script>
</head>
<body>
<!-- Original table visible on normal view -->
<table id="originalTable">
<tr>
<td class="original-cell"><div class="cell-content">Column 1</div></td>
<td class="original-cell"><div class="cell-content">Column 2</div></td>
<td><div class="cell-content">Column 3</div></td>
</tr>
<tr>
<td><div class="cell-content">Data 1</div></td>
<td><div class="cell-content">Data 2</div></td>
<td><div class="cell-content">Data 3</div></td>
</tr>
<tr>
<td><div class="cell-content">Data 4</div></td>
<td><div class="cell-content">Data 5</div></td>
<td><div class="cell-content">Data 6</div></td>
</tr>
<tr>
<td><div class="cell-content">Data 7</div></td>
<td><div class="cell-content">Data 8</div></td>
<td><div class="cell-content">Data 9</div></td>
</tr>
<!-- Add more rows as needed -->
</table>
<!-- Transformed table visible on mobile view -->
<table id="transformedTable" style="border: 2px solid black">
</table>
</body>
</html>
2
Answers
This can be one way of doing that:
You can do this without using js: