HTML Tokenization and Tree Construction
From characters to tokens to nodes
After byte decoding, the tokenizer reads characters and emits tokens for tags, text, comments and doctype. The tree builder uses tokens and its current insertion mode to construct nodes. Tokens are not DOM nodes; there is no standard API exposing the browser token stream. The example inspects only the resulting child nodes.
<output id="result"></output><script> const parsed = new DOMParser().parseFromString("<p>A<!--note--><em>B</em></p>", "text/html"); const result = [...parsed.querySelector("p").childNodes].map(n => n.nodeType).join(","); document.querySelector("#result").textContent = String(result);</script>Expected output: 3,8,1
Tokenizer states change interpretation
Text in a textarea uses the RCDATA state: character references are decoded, but ordinary tag-looking text is not treated as element markup. In a normal paragraph, the same tag becomes an element. Raw-text contexts such as style follow different rules again.
<output id="result"></output><script>const parsed = new DOMParser().parseFromString("<textarea>& <b>Hi</b></textarea><p>& <b>Hi</b></p>", "text/html");const result = parsed.querySelector("textarea").value + " | " + parsed.querySelector("p").textContent;document.querySelector("#result").textContent = String(result);</script>Expected output: & <b>Hi</b> | & Hi
Fragment parsing needs a context
The tree builder uses context-specific insertion modes. Setting innerHTML on a table invokes fragment parsing in table context, so a row can cause an implicit tbody. This is not equivalent to concatenating DOM nodes manually. Use only trusted static markup in this experiment.
<output id="result"></output><script> const table = document.createElement("table"); table.innerHTML = "<tr><td>One</td></tr>"; const result = table.firstElementChild.localName; document.querySelector("#result").textContent = String(result);</script>Expected output: tbody
Common mistakes and practice
Do not attempt to parse general HTML with a simple regular expression. Inspect the DOM after parsing, not only the input string. Detached documents in these examples are for trusted test fixtures, not sanitizers; untrusted markup is covered later.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
HTML Tokenization and Tree Construction — Knowledge Check
Apply the internals concepts taught in this lesson.
What comes before tree construction?
Are tokens DOM nodes?
How is & in textarea interpreted?
What does childNodes include that children excludes?
Why can table.innerHTML produce tbody?