Categories
JavaScript Answers

How to Create an HTML Table Using JavaScript?

Spread the love

We can create an HTML table with the document.createElement method.

For instance, if we have the following HTML:

<div>

</div>

Then we can create the table and attach it to the div by writing:

const div = document.querySelector("div");
const table = document.createElement('table');
table.border = '1';
const tableBody = document.createElement('tbody');
table.appendChild(tableBody);

for (let i = 0; i < 3; i++) {
  const tr = document.createElement('tr');
  tableBody.appendChild(tr);
  for (let j = 0; j < 4; j++) {
    const td = document.createElement('td');
    td.width = '75';
    td.appendChild(document.createTextNode(`cell ${i}-${j}`));
    tr.appendChild(td);
  }
}
div.appendChild(table);

We get the div with document.querySelector .

Then we create the table element with:

const table = document.createElement('table');

We set the border width in pixels with:

table.border = '1';

Then we create the tbody element with:

const tableBody = document.createElement('tbody');

Next, we append the tbody element to the table with:

table.appendChild(tableBody);

Then we add the tr and td elements into the tr with:

for (let i = 0; i < 3; i++) {
  const tr = document.createElement('tr');
  tableBody.appendChild(tr);
  for (let j = 0; j < 4; j++) {
    const td = document.createElement('td');
    td.width = '75';
    td.appendChild(document.createTextNode(`cell ${i}-${j}`));
    tr.appendChild(td);
  }
}

We create the table row element with:

const tr = document.createElement('tr');

Then we attach it to the tbody with:

tableBody.appendChild(tr);

Then we have another loop inside to add the td and append the td in the tr as its child:

for (let j = 0; j < 4; j++) {
  const td = document.createElement('td');
  td.width = '75';
  td.appendChild(document.createTextNode(`cell ${i}-${j}`));
  tr.appendChild(td);
}

We set the width of the td and call document.createTextNode and td.appendChild to add the text inside the td .

Then tr.appendChild(td) add the td as the last child of tr .

Finally, we add the table into the div with:

div.appendChild(table);

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *