HTML JS

GET HTML TABLE DATA IN JAVASCRIPT

(quick guide & examples)

<table id="demo">   <tr>     <th>Name</th> <th>Email</th>   </tr>   <tr>     <td>Joa Doe</td> <td>joa@doe.com</td>   </tr>   <tr>     <td>Job Doe</td> <td>job@doe.com</td>   </tr> </table>

DUMMY HTML TABLE

01

var data = []; for (let row of document. querySelectorAll("#demo tr")) {   APPEND DATA ROW   data.push([]);   let r = data.length - 1;

TABLE TO ARRAY

02

  APPEND CELL VALUES   let cells = row.querySelectorAll("td");   if (cells.length == 0)   { cells = row.querySelectorAll("th"); }   for (let cell of cells)   { data[r].push(cell.innerHTML); }  }

INIT DATA var rows = data = {}, map = [], cells, document.querySelectorAll("#demo tr");

TABLE TO OBJECT

03

LOOP THROUGH HEADER CELLS cells = rows[0].querySelectorAll("th"); for (let header of cells) {   data[header.innerHTML] = [];   map.push(header.innerHTML); }

LOOP THROUGH DATA ROWS for (let r=1; r<rows.length; r++) {   cells = rows[r].querySelectorAll("td");   for (let [i,cell] of Object.entries(cells))   { data[map[i]].push(cell.innerHTML);  }  }