Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why all <tr> go in <thead> after calling a createTHead

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();

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

cf https://jsfiddle.net/n1b87vt3/

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading