Skip to content

Instantly share code, notes, and snippets.

@seantunwin
Created February 20, 2020 21:49
Show Gist options
  • Save seantunwin/c32cc55d35c22aa932740e42a89d0bac to your computer and use it in GitHub Desktop.
Save seantunwin/c32cc55d35c22aa932740e42a89d0bac to your computer and use it in GitHub Desktop.
Get cell contents from an HTML table
/* Table structure
<table>
<tr>
<th>Email</th>
<th>Username</th>
</tr>
<tr>
<td>fake@data.com</td>
<td>UsernameHere</td>
</tr>
<tr>
<td>test@test.com</td>
<td>FakeUserame</td>
</tr>
<tr>
<td>foo@bar.com</td>
<td>helloworld</td>
</tr>
<tr>
<td>so@email.com</td>
<td>SOuser123</td>
</tr>
<tr>
<td>hello@world.com</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
[
[
"fake@data.com",
"UsernameHere"
],
[
"test@test.com",
"FakeUserame"
],
[
"foo@bar.com",
"helloworld"
],
[
"so@email.com",
"SOuser123"
],
[
"hello@world.com",
"TreesAreGreen"
]
]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment