Categories
JavaScript Answers

How to create table using JavaScript?

Spread the love

Sometimes, we want to create table using JavaScript.

In this article, we’ll look at how to create table using JavaScript.

How to create table using JavaScript?

To create table using JavaScript, we can use the insertRow and insertCell methods.

For instance, we write

const createTable = (row, col) => {
  let body = document.body;
  let tbl = document.createElement("table");

  for (let i = 0; i < row; i++) {
    let tr = tbl.insertRow();
    for (let j = 0; j < col; j++) {
      let td = tr.insertCell();
      td.appendChild(document.createTextNode(`${i},${j}`));
      td.style.border = "1px solid black";
    }
  }
  body.appendChild(tbl);
};

createTable(5, 5);

to create the table element with createElement.

Then we create a nested for loop to create the rows and cells and put them in the table.

We call tbl.insertRow to insert a tr element.

And then we call tr.insertCell to insert a td element into the tr element.

Then we call createTextNode to create a text node and call td.appendChild to append the text node as its child.

Finally, we call body.appendChild to append the table as the child of the body.

Conclusion

To create table using JavaScript, we can use the insertRow and insertCell methods.

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 *