Consider the following invalid HTML, where <tr>
is a direct child of <div>
:
console.log(document.getElementsByTagName('tr').length);
<div>
<tr></tr>
</div>
The <tr>
element does not get added to the DOM.
Now consider the equally-invalid HTML, where <tr>
is a direct child of <table>
:
console.log(document.getElementsByTagName('tr').length);
<div>
<table>
<tr></tr>
</table>
</div>
This time, the <tr>
element does get added to the DOM.
Note that I have deliberately omitted the <tbody>
in the second snippet, which is required to form valid markup. If omitted, <tbody>
is automatically added by the browser, as is noted in this question.
This answer mentions the official W3 documentation's fairly extensive list on what tags are optional, but why are these particular tags optional? Considering the browser is smart enough to automatically add the <tbody>
element that I have omitted, why is it not smart enough to add the <table>
element as well? There is no possible ambiguity, as <table>
is the only valid parent for <tbody>
.
Why can <tbody>
be inferred from <tr>
, but not <table>
? Can only one level of DOM hierarchy be inferred?
Historically tables used to be created with a table and rows and no tbody
or thead
elements at all.
Even the reference you pointed to that said tbody
is "required" does not in fact say that at all. The very next sentence says the start tag is optional if the first element after the table
is a `tr.
Also see here:
https://www.w3.org/TR/html5/tabular-data.html#the-tbody-element
Which is official and states the same:
A tbody element's start tag may be omitted if the first thing inside the tbody element is a tr elemen
The optionality of tags to a large extent comes from the fact that html used to commonly be written a lot sloppier, with no concept of an empty tag like <br />
and very commonly not requiring closing tags such as with <li>
.
There was an attempt after HTML 4 to create XHTML standard that was a lot stricter and didn't have most (or any?) of the optionality and enforced strict XML conformance for html. This never fully took off and html5 went fully the opposite direction codifying the fact that HTML is not necessarily XML.