Full answer
The HTML parser never stops with a syntax error. It follows a fixed algorithm that repairs mistakes, and the result is a DOM tree that is always valid. Two kinds of repair matter.
Implied elements: some elements can be left out, and the parser adds them.
html,headandbodyare created even when the source has none. A page that starts with<title>Hi</title><p>textgets all three.tbodyis added inside atablewhen rows appear without it. This is why the selectortable > trnever matches, whiletable > tbody > trdoes.- Optional end tags: a
liis closed when the nextlistarts, apis closed when a block element such as anotherpor adivstarts, andtdandtrend when the next cell or row begins.
Error recovery: when the markup breaks the rules, the parser picks a repair. For example, a p cannot contain a div, so the div closes the paragraph and the later </p> creates an empty paragraph. Another rule moves a misplaced element out of a table. The exact rules are in the specification, and every browser follows the same ones, so the DOM is the same everywhere.
What this means in practice:
- The source and the DOM can differ, so debug in the Elements panel and not in the file.
- CSS and scripts see the DOM. A child selector written for the source can fail.
- Leaving out optional tags is legal, but writing them makes the structure clear to readers.
The list has two li elements, because each one is closed by the next. The two paragraphs are siblings, and the second is not inside the first. The table gets a tbody that is not in the source. A document parsed from a tiny string still has head and body.
If a layout bug looks impossible, compare the source with the DOM before changing any CSS.
<ul id="u"><li>One<li>Two</ul>
<p id="p1">First<p id="p2">Second
<table id="t"><tr><td>cell</table>
<script>
window.doc = new DOMParser().parseFromString("<title>Hi</title><p>text", "text/html");
</script>Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.
Key points
- The parser repairs errors and always builds a tree.
- html, head, body and tbody are implied.
- li, p, td and tr end tags are optional.
- All browsers follow the same algorithm.
- Debug in the DOM, not in the source.
Common mistakes
- Writing the selector table > tr and finding no match.
- Debugging from the source file and ignoring the DOM that the parser built.
- Relying on optional end tags in a team that does not know the rules.
Follow-ups
- Why does a missing end tag on a p not nest the next p inside it?
- Which tool shows the real DOM?
Tips
- Say that the parser always produces a tree and never throws a syntax error.
- Give the tbody example, because it breaks child selectors.