Get All Table Cell Value with JavaScript

02/04/2022
Contents
In this article, you will learn how to get all table cell value with JavaScript.
Count table rows and columns
You can get the number of rows and columns of the table by using the rows property and cells property of HTMLTableElement which is the obtained table element.
// Get table element
let myTable = document.getElementById('targetTable');
// Count table rows
let totalRowCount = myTable.rows.length;
// Count table columns
let totalColumnCount = myTable.rows[i].cells.length;
Now you know the number of rows and columns in the table.
Get all table cell value
Below is a sample code to get the values of all the cells in the table.
Use a loop to get the values of all cells.
let myTable = document.getElementById('targetTable');
for (let row of myTable.rows) {
for(let cell of row.cells){
console.log(cell.innerText);
}
}
You can also get the values of all cells in the table by the following method.
let myTable = document.getElementById('targetTable');
let cells = myTable.querySelectorAll('td');
cells.forEach( (cell) => console.log(cell.innerHTML));