HTML Parser Error Recovery
Paragraphs can close implicitly
This source may look as if the div is nested inside a paragraph, but the omitted p end tag is permitted in this context. The start tag for div closes the open p in normal body parsing. DOM inspection reveals that they are siblings. Write separate paragraphs and flow containers instead.
<output id="result"></output><script> const parsed = new DOMParser().parseFromString("<p>Intro<div>Block</div>", "text/html"); const result = parsed.body.innerHTML; document.querySelector("#result").textContent = String(result);</script>Expected output: <p>Intro</p><div>Block</div>
Table foster parenting
The intentionally invalid example places text directly in a table. In this situation the tree builder uses foster parenting: non-whitespace text is inserted outside the table, before it here. Put the text in a cell or a caption instead.
<output id="result"></output><script> const parsed = new DOMParser().parseFromString("<table>Note<tr><td>A</td></tr></table>", "text/html"); const result = parsed.body.firstChild.textContent + " / " + parsed.querySelector("table").firstElementChild.localName; document.querySelector("#result").textContent = String(result);</script>Expected output: Note / tbody
Misnested formatting elements
The adoption agency algorithm repairs certain misnested formatting elements. In the deliberately invalid source below, i continues after b ends, producing two i elements. This behavior is specified, but should not be used to design markup. Close nested formatting elements in reverse order.
<output id="result"></output><script> const parsed = new DOMParser().parseFromString("<b>Bold <i>both</b> italic</i>", "text/html"); const result = parsed.body.innerHTML; document.querySelector("#result").textContent = String(result);</script>Expected output: <b>Bold <i>both</i></b><i> italic</i>
Common mistakes and practice
Inspect source and Elements/DOM views side by side; the parser is not a full conformance checker. Use an HTML validator in addition to testing runtime behavior. A repair can break event delegation or CSS selectors that assumed the original nesting.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
HTML Parser Error Recovery — Knowledge Check
Apply the internals concepts taught in this lesson.
What normally happens when a div start tag is seen inside p?
What is foster parenting in a table?
Which algorithm repairs some misnested formatting tags?
Does error recovery make the source conforming?
How should nested formatting tags be closed?