# html/parse Parse an HTML document into a Deft tree. WHATWG-compliant tag-soup recovery: unclosed and stray tags, misnesting, and mangled tables recover the way a browser recovers, and character references (named like `&`, numeric like `😀`) are decoded in text and attributes during the parse. ## Syntax
[html/parse $src ?opts]
## Parameters - `$src` — HTML source text (string; treated as UTF-8 unless `:encoding`) - `$opts` — optional map: - `:encoding` — `"windows-1252"`-style charset label to re-decode the bytes first (WHATWG label aliasing applies: `iso-8859-1` is windows-1252), or `:auto` to prescan the first 1024 bytes for a BOM or `<meta charset>` declaration - `:fragment true` — parse in `<body>` context (innerHTML semantics) instead of building a document ## Examples
set doc [html/parse "<p class='x'>Hello <b>world</b>!</p>" %{ :fragment true}]
$doc~tag                     # => "p"
$doc~attrs~class             # => "x"
[nth $doc~children 0]        # => "Hello "
[nth $doc~children 1]~tag    # => "b"

# Tag soup recovers: unclosed <li>, missing </p>
set f [html/parse "<ul><li>one<li>two</ul>" %{ :fragment true}]
[len [nth $f 0]~children]    # => 2

# Charset re-decode from a mail body
set latin1 [|printf "<p>caf\xe9</p>"]
[html/parse $latin1 %{ :encoding "iso-8859-1" }]~tag  # => "html"
## Returns Elements are `%{ :tag "div" :attrs %{ :class "x" } :children @{ ... } }`; `:children` holds document-order content: text strings, element maps, `%{ :comment "..." }`, and `%{ :doctype "html" ... }` (with optional `:public-id` / `:system-id`). Root collapse: a parse with exactly one top-level element returns that element's map directly — `<div><p>hi</p></div>` yields the `<html>` element map. Anything else (a doctype, top-level comments, fragments with several roots) returns a vector of top-level nodes. Failure returns `%Err{ :message "..." }` (unknown encoding name, source above 64 MiB, nesting beyond 1024). The parser itself never fails on malformed markup — it repairs it. ## See Also `html/open`, `html/text`, `html/select`, `html/serialize`, `html/decode-entities`, `xml/parse`