I have a question regarding this code:
const table = document.createElement("TABLE");
const thead = table.createTHead();
const tr = thead.insertRow();
const th1 = tr.insertCell();
th1.textContent = "header1";
const th2 = tr.insertCell();
th2.textContent = "header2";
const tr2 = table.insertRow();
const td1= tr2.insertCell();
td1.textContent = "field1";
const td2 = tr2.insertCell();
td2.textContent = "field2";
document.getElementById("main").appendChild(table);
All rows insert in table (not in header) go in <thead>. Why?
Why they are not going in a <tbody> (or a least outside of this <thead> as I am not doing a thead.insertRow() but a table.insertRow();
cf https://jsfiddle.net/n1b87vt3/
Because you didn't create a <tbody>, so you insert all in <thead>. Add also tbody const tbody = table.createTBody() then insert the new row in it tbody.insertRow():
const table = document.createElement("TABLE");
const thead = table.createTHead();
const tr = thead.insertRow();
const th1 = tr.insertCell();
th1.textContent = "header1";
const th2 = tr.insertCell();
th2.textContent = "header2";
const tbody = table.createTBody();
const tr2 = tbody.insertRow();
const td1= tr2.insertCell();
td1.textContent = "field1";
const td2 = tr2.insertCell();
td2.textContent = "field2";
document.getElementById("main").appendChild(table);
td {
border: 1px solid black;
}
thead {
color: red;
}
<html>
<body>
<div id="main">
</div>
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With