Created
February 20, 2020 21:49
-
-
Save seantunwin/c32cc55d35c22aa932740e42a89d0bac to your computer and use it in GitHub Desktop.
Get cell contents from an HTML table
This file contains hidden or 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
/* Table structure | |
<table> | |
<tr> | |
<th>Email</th> | |
<th>Username</th> | |
</tr> | |
<tr> | |
<td>[email protected]</td> | |
<td>UsernameHere</td> | |
</tr> | |
<tr> | |
<td>[email protected]</td> | |
<td>FakeUserame</td> | |
</tr> | |
<tr> | |
<td>[email protected]</td> | |
<td>helloworld</td> | |
</tr> | |
<tr> | |
<td>[email protected]</td> | |
<td>SOuser123</td> | |
</tr> | |
<tr> | |
<td>[email protected]</td> | |
<td>TreesAreGreen</td> | |
</tr> | |
</table> | |
*/ | |
function getTableData(table) { | |
let tableData = []; // Store for table contents | |
let hasHeaders = false; // Store whether table has th in a row (first row assumed) | |
// Loop through each table row | |
[...table.querySelectorAll('tr')].forEach((row, ri) => { | |
// Go to next row when row doesn't start with a td | |
if (row.children[0].tagName !== 'TD') { | |
hasHeaders = true; | |
return; | |
} | |
// Create an empty child Array | |
tableData.push([]); | |
// Loop over each row cell | |
[...row.getElementsByTagName('td')].forEach((cell, ci) => { | |
// Reset the row index when headers exist | |
const rowIndex = (hasHeaders) ? ri - 1 : ri; | |
tableData[rowIndex][ci] = cell.textContent; | |
}); | |
}); | |
} | |
const tableContents = getTableData(document.querySelector('table')); | |
document.write(`<pre>${JSON.stringify(tableData, null, ' ')}</pre>`); | |
/* Result | |
[ | |
[ | |
"[email protected]", | |
"UsernameHere" | |
], | |
[ | |
"[email protected]", | |
"FakeUserame" | |
], | |
[ | |
"[email protected]", | |
"helloworld" | |
], | |
[ | |
"[email protected]", | |
"SOuser123" | |
], | |
[ | |
"[email protected]", | |
"TreesAreGreen" | |
] | |
] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment