Last active
September 21, 2022 01:26
-
-
Save snosrap/9bcd24d7afce5c4607d6168bb045651a to your computer and use it in GitHub Desktop.
Convert HTMLTableElement (with rowSpan and colSpan) into a JavaScript Array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script type="text/javascript"> | |
HTMLTableElement.prototype.fp_toTable = function(nullvalue = null) { | |
var columnCount = Array.from(this.rows).map(row => Array.from(row.cells).reduce((sum, cell) => sum + cell.colSpan, 0)).reduce((max, row) => Math.max(max, row), 0); | |
var itemCount = Array.from(this.rows).reduce((rsum, row) => rsum + Array.from(row.cells).reduce((csum, cell) => csum + (cell.colSpan * cell.rowSpan), 0), 0); | |
var rowCount = itemCount / columnCount; | |
var items = Array.apply(null, Array(itemCount)); | |
tds = Array.from(this.getElementsByTagName('td')); | |
for(var i=0, ii=0; i<tds.length; i++, ii=items.indexOf(undefined, i)) { | |
items[ii] = tds[i].innerText; | |
for(var j=0;j<tds[i].colSpan;j++) { | |
for(var k=0;k<tds[i].rowSpan;k++) { | |
if(j||k) { | |
items[ii + j + (k * columnCount)] = nullvalue; | |
} | |
} | |
} | |
} | |
return Array.from(Array(rowCount).keys()).map(r => items.slice(r*columnCount, (r+1)*columnCount)); | |
}; | |
</script> | |
<style type="text/css">td{vertical-align:top;}</style> | |
<table border="1" id="table"> | |
<tr> | |
<td>A</td> | |
<td>B</td> | |
<td>C</td> | |
</tr> | |
<tr> | |
<td colspan="2" rowspan="2">D</td> | |
<td>E</td> | |
</tr> | |
<tr> | |
<td>F</td> | |
</tr> | |
<tr> | |
<td>G</td> | |
<td rowspan="3" colspan="2">H</td> | |
</tr> | |
<tr> | |
<td>I</td> | |
</tr> | |
<tr> | |
<td>J</td> | |
</tr> | |
</table> | |
<script type="text/javascript"> | |
var table = document.getElementById('table'); | |
console.table(table.fp_toTable()); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment