groznyj
groznyj

Reputation: 63

Why do the <tr> elements of a <table> beyond the first not increase the table's childElementCount?

I am learning the JavaScript DOM and could not understand the following behavior:

let test = document.getElementById("test");
console.log(test.childElementCount);
<table id="test">
  <tr></tr>
  <tr></tr>
</table>

I thought that the table would have two child elements (two tr) but it seems to only have one. This is the case no matter how many tr are added beyond the first.

Upvotes: 3

Views: 72

Answers (2)

David
David

Reputation: 218960

Because the browser is correcting the HTML structure for you. Add some content to the rows so you can right-click on them and inspect the element:

let test = document.getElementById("test");
console.log(test.childElementCount);
<table id="test">
  <tr><td>1</td></tr>
  <tr><td>2</td></tr>
</table>

You'll find that the actual HTML in the DOM is:

<table id="test">
  <tbody>
    <tr><td>1</td></tr>
    <tr><td>2</td></tr>
  </tbody>
</table>

To be fair, MDN does say that "one or more <tr> elements" are a permitted child of a <table> element. Perhaps this differs by the HTML version specified or inferred, I'm not really certain. But either way that's what the browser is doing.

Upvotes: 5

Avinash Dalvi
Avinash Dalvi

Reputation: 9301

The ParentNode.childElementCount read-only property returns an unsigned long representing the number of child elements of the given element. Any modern browser if you are missing <tbody> its adds while rendering you can see console of test value. If you add <thead> its will return 2 as count. So for table its 2 child if you have <tbody> and <thead>. In your case only <tbody> by default.

let test = document.getElementById("test");
console.log(test);
console.log(test.childElementCount);
<table id="test">
<thead>
</thead>
 <tbody>
  <tr></tr>
  <tr></tr>
  <tr></tr>
  </tbody>
 
</table>

Upvotes: 0

Related Questions