javascript – Retrieve data from a table


I have generated a table and now I would like that when I hit a button I could retrieve each row of the table to be able to store it.

<table id="asistencias" class="table">
        <thead class="thead-dark">
              <td><input id="55" type="checkbox" checked=""></td>
              <td><input id="5" type="checkbox" checked=""></td>

In this case I only have 2 rows but it would be for several rows to obtain. And I don't know how to do this.


To obtain data from a table you can perform a search by selector or any other type, iterating through rows and then columns:

 let atributos = []; document.querySelectorAll('#asistencias thead th').forEach(elemento => { atributos.push(elemento.innerText); }); let datos = []; /* Iteramos por cada fila */ document.querySelectorAll('#asistencias tbody tr').forEach(fila => { /* Rellenamos los campos con datos vacíos */ let dato = {}; atributos.forEach(campo => { dato[campo] = ''; }); /* Iteramos por cada columna */ fila.querySelectorAll('td').forEach((elemento, n) => { let input = elemento.querySelector('input'); /* Si tiene un input almacenamos su valor */ if (input !== null) { dato[atributos[n]] = input.checked; =; } else { dato[atributos[n]] = elemento.innerText; } }); datos.push(dato); }); console.log(datos);
 <table id="asistencias" class="table"> <thead class="thead-dark"> <tr> <th>Nombre</th> <th>Habitual</th> <th>Fichar</th> </tr> </thead> <tbody> <tr> <td>Raul</td><td>x</td><td><input id="55" type="checkbox" /></td> </tr> <tr> <td>Paco</td><td>x</td><td><input id="5" type="checkbox" checked="" /></td> </tr> <tr> <td>José</td><td>x</td><td><input id="7" type="checkbox" /></td> </tr> </tbody> </table>

In this code I make a previous pass through each column of the header to find out what each column contains and thus be able to assign each row a property in the dato class instead of numerical indexes.

Scroll to Top