Sometimes, we want to create a table with JavaScript.
In this article, we’ll look at how to create a table with JavaScript.
How create a table with JavaScript?
To create a table with JavaScript, we can use the document.createElement
and document.createTexNode
methods.
For instance, we write:
const table = document.createElement('table');
for (let i = 1; i < 5; i++) {
const tr = document.createElement('tr');
const td1 = document.createElement('td');
const td2 = document.createElement('td');
const text1 = document.createTextNode('Text1');
const text2 = document.createTextNode('Text2');
td1.appendChild(text1);
td2.appendChild(text2);
tr.appendChild(td1);
tr.appendChild(td2);
table.appendChild(tr);
}
document.body.appendChild(table);
We call document.createElement
to create the table element.
Then we add a for loop to create the tr element and the td elements inside the tr.
We create the tr and tds with document.createElement
.
Next, we create the text nodes for the td elements with document.createTextNode
.
Then we call appendChild
to append the text nodes to the tds and append the tds to the trs.
Finally, we call table.appendChild
to append the tr to the table element.
And we call document.body.appendChild
with table
to append the table to the body element.
Conclusion
To create a table with JavaScript, we can use the document.createElement
and document.createTexNode
methods.