Tree Construction

Tree Construction

Tree construction is the second parsing stage: it consumes the tokenizer’s stream and builds the DOM according to the standards algorithm — including its famous error-recovery behaviours. parse_html() wraps the whole pipeline in one call; TreeBuilder exposes the machinery.


One-Call Parsing

parse_html() goes from markup text to a finished tree; parse_fragment() applies the fragment algorithm against a context element. Both drive the same TreeBuilder internals via TreeBuilder.run().

Insertion Modes and Open Elements

InsertionMode models the algorithm’s mode machine, with StackOfOpenElements and TemplateInsertionModeStack tracking construction state exactly as the specification describes.

Error Recovery

Misnested formatting elements resolve through run_adoption_agency_algorithm() — the standard’s adoption agency algorithm — and ActiveFormattingList tracks active formatting elements. get_foster_parent_location() implements foster parenting for misplaced table content.

Quirks and Foreign Content

determine_quirks_mode() classifies documents from their doctype. SVG and MathML content route through adjust_svg_attributes(), adjust_mathml_attributes(), and adjust_foreign_attributes(), with integration points detected by is_html_integration_point() and is_mathml_text_integration_point().


Tips and Best Practices

  • Reach for parse_html() unless you specifically need construction-state introspection
  • Use parse_fragment() with the right context element — fragment parsing rules depend on it
  • When debugging surprising trees from bad markup, the adoption agency and foster-parenting behaviours are usually the explanation, not a bug

Common Issues

IssueCauseFix
Table content moved outside the tableFoster parenting of misplaced contentFix the source markup nesting
Formatting tags duplicated in outputAdoption agency reconstructionExpected standards behaviour for misnesting
Document renders in quirks modeMissing or legacy doctypeCheck determine_quirks_mode() on the input

FAQ

Why does malformed markup produce a valid tree?

The standards algorithm defines recovery for every error case — TreeBuilder implements those paths rather than raising.

What is the adoption agency algorithm?

The standard’s procedure for repairing misnested formatting elements; exposed as run_adoption_agency_algorithm().

Does the builder handle SVG and MathML?

Yes — foreign content attributes adjust via the dedicated adjust_*_attributes() functions with standards integration-point detection.


API Reference Summary

Class/MethodDescription
parse_htmlMarkup to tree in one call
parse_fragmentFragment algorithm parsing
TreeBuilder.runRun tree construction
InsertionModeAlgorithm mode machine
run_adoption_agency_algorithmMisnesting repair
determine_quirks_modeDoctype-based quirks classification

See Also