Is it possible to insert data from a JS array into a ready-made HTML table?

Asked

Viewed 207 times

0

Good night guys, once again here came a doubt.

I have a table ready (and empty) on the page HTML, and I’d like to fill it out using JS, is it possible? I’ll leave the code below for better understanding:

HTML

<table class="table table-bordered" id="tableClient">
    <thead>
      <tr>
        <th scope="col">Nome</th>
        <th scope="col">Email</th>
        <th scope="col">CPF</th>
        <th scope="col">Criado em</th>
      </tr>
    </thead>
    <tbody>
      
        <tr>
        <td id="name"></td>
        <td id="email"></td>
        <td id="cpf"></td>
        <td id="created"></td>
      </tr>
    </tbody>
  </table>

I’d like to fill in each column, name, email, Cpf, created using arrays created, but unfortunately I could not find anything similar to give me a light..

I’m grateful for anyone who can help me!

  • Yes it is possible.

  • Whoa, what’s up Augusto, baby? Could you give me an example of how to do that? I don’t want to be lazy, but I couldn’t find anything like it that could help me..

1 answer

1


1 - You use Document.createelement() to create tr and the td.

2 - Uses . textContent to define the content of tds.

3 - Use . appendchild() to place the tds within the tr and put the td within the tbody.

var nome = 'Fulano';
var email= 'coisodostreco@gmailcom';
var cpf= '555.555.555-55';
var data= '01/01/2020';


var corpoTabela = document.querySelector('tbody');

var tr= document.createElement('tr');
var tdNome= document.createElement('td');
var tdEmail= document.createElement('td');
var tdCPF= document.createElement('td');
var tdData= document.createElement('td');

tdNome.textContent = nome;
tdEmail.textContent = email;
tdCPF.textContent = cpf;
tdData.textContent = data;

tr.appendChild(tdNome);
tr.appendChild(tdEmail);
tr.appendChild(tdCPF);
tr.appendChild(tdData);
corpoTabela.appendChild(tr);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.