HTML Syntax, DOCTYPE, Tokenization and Parsing
How WHATWG HTML defines markup syntax, DOCTYPE, and the tokenizer and tree builder that turn bytes into a DOM.
This page summarizes the WHATWG HTML Living Standard on document syntax and on parsing HTML documents. The developer-oriented edition at syntax for web developers matches the normative syntax rules. Where you transform HTML at the edge, Cloudflare HTMLRewriter exposes parsed doctype fields that align with the same token model.
DOCTYPE: why every HTML document starts with one
Section titled “DOCTYPE: why every HTML document starts with one”A DOCTYPE is a required preamble. Including it helps the browser follow the relevant specifications; omitting it tends to push rendering into a legacy mode that does not match modern HTML.
DOCTYPEs are required for legacy reasons. When omitted, browsers tend to use a different rendering mode that is incompatible with some specifications. Including the DOCTYPE in a document ensures that the browser makes a best-effort attempt at following the relevant specifications.
— WHATWG, 13.1.1 The DOCTYPE
In practice you write <!DOCTYPE html> (ASCII case-insensitive). Generators that cannot emit that short form may use <!DOCTYPE html SYSTEM "about:legacy-compat"> (or single quotes); the legacy string should not be used unless required.
During parsing, the first DOCTYPE token is handled in the initial insertion mode. If the token’s name is not html, or identifiers do not match the modern pattern, the document may enter quirks mode or limited-quirks mode—affecting layout details such as how width and height are interpreted. A correct <!DOCTYPE html> avoids those legacy paths.
| What you write | Parser takes away |
|---|---|
<!DOCTYPE html> |
Name html; standard-mode document (when other conditions allow) |
| Missing or broken DOCTYPE | Parse error; quirks mode likely |
| Legacy public/system identifiers | May trigger quirks or limited-quirks per the spec’s identifier lists |
Start tags, end tags, and text that must not look like markup
Section titled “Start tags, end tags, and text that must not look like markup”Start tags begin with <, then the element’s tag name, optional attributes separated by ASCII whitespace, optional trailing / on void or foreign elements, and >. End tags use </, the tag name, optional space, and >.
The first character of a start tag must be a U+003C LESS-THAN SIGN character (
<). The next few characters of a start tag must be the element’s tag name.— WHATWG, 13.1.2.1 Start tags
On void HTML elements, a / before > is unnecessary and has no effect; if it sits directly after an unquoted attribute value, the solidus becomes part of the value—not the tag closer. Prefer quoted attributes and explicit > closers.
Inside raw text and escapable raw text elements (for example script, style, textarea, title), text must not contain a substring that looks like an end tag for that element: </ + tag name + whitespace, >, or /. That is why </script> inside a script string breaks parsing unless escaped or split (for example with < + '/script>').
Character references: &name;, &#digits;, &#xhex;
Section titled “Character references: &name;, &#digits;, &#xhex;”Character references escape characters that cannot appear literally in text. They start with & and take one of three forms: named (&), decimal numeric (&), or hexadecimal numeric (&).
Character references must start with a U+0026 AMPERSAND character (&). Following this, there are three possible kinds of character references: Named character references … Decimal numeric character reference … Hexadecimal numeric character reference
— WHATWG, 13.1.4 Character references
Named references use exact case from the named-character table and should end with ;. Without a semicolon, the tokenizer may still resolve the reference (with a parse error) in text, but in attributes a missing semicolon followed by = or an alphanumeric can leave the &… sequence unchanged—for historical compatibility.
Numeric references cannot produce carriage return (U+000D), noncharacters, or most control characters; invalid codes often become the replacement character U+FFFD. Windows-1252 “numeric entities” in the 0x80–0x9F range are remapped per the spec’s table during tokenization.
An ambiguous ampersand is & + alphanumerics + ; that does not match any named reference—treated as an error case the tokenizer resolves according to context.
Comments, CDATA, and processing instructions in HTML syntax
Section titled “Comments, CDATA, and processing instructions in HTML syntax”Comments use <!-- … -->. Comment text must not start with > or ->, must not contain <!--, -->, or --!>, and must not end with <!- (but may end with <!).
CDATA sections (<![CDATA[ … ]]>) are valid only in foreign content (MathML or SVG), not in normal HTML body markup. In HTML, a [CDATA[ declaration in markup is a parse error and becomes comment-like bogus data.
Processing instructions look like <?target data?>, but in HTML, <?xml …?> and <?xml-stylesheet …?> are not real processing instructions—they become bogus comments. HTML also allows > or ?> as the closing delimiter, unlike XML.
Parsing model: tokenization, then tree construction
Section titled “Parsing model: tokenization, then tree construction”The input to HTML parsing is a stream of code points. The parser runs tokenization (a state machine starting in the data state), then tree construction, which updates a Document and its DOM.
The input to the HTML parsing process consists of a stream of code points, which is passed through a tokenization stage followed by a tree construction stage. The output is a Document object.
— WHATWG, 13.2.1 Overview of the parsing model
Before tokenization, newlines are normalized to line feed (LF). CR, bare LF, and CRLF in the source are equivalent at this stage. Surrogates, noncharacters, and most control characters in the input stream are parse errors.
The tokenizer emits DOCTYPE, start tag, end tag, comment, character, and end-of-file tokens. Each emitted token is handled immediately by the tree builder; the tree builder can pause tokenization (for example when a script runs and calls document.write()).
Insertion mode: how the tree builder decides what to do
Section titled “Insertion mode: how the tree builder decides what to do”Insertion mode is the main state of the tree construction stage. It starts as initial, then moves through modes such as before html, before head, in head, after head, in body, table-related modes (in table, in cell, …), and after body.
The insertion mode is a state variable that controls the primary operation of the tree construction stage.
— WHATWG, 13.2.4.1 The insertion mode
The parser also keeps a stack of open elements, a list of active formatting elements (for mis-nested formatting tags, with “Noah’s Ark” limits of three identical formatting elements after the last marker), head and form element pointers, and—for template—a stack of template insertion modes.
Tokens in foreign content (SVG/MathML) use separate rules when the current node is not an integration point; HTML start tags inside foreign content can bounce processing back to the current HTML insertion mode after closing foreign elements.
RAWTEXT, RCDATA, and script: tokenizer modes tied to elements
Section titled “RAWTEXT, RCDATA, and script: tokenizer modes tied to elements”When the tree builder sees certain start tags, it switches the tokenizer:
- Raw text (
script,style, …) →RAWTEXT(no character references except via tag-like boundaries). - RCDATA (
textarea,title, …) → character references allowed; end tags detected like RCDATA. scriptadditionally implements the “escaped” and “double escaped” substates so patterns such as<!--…-->inside script source do not close the element early.
Entering those elements sets insertion mode to text until the matching end tag (with special script execution and parser pause behavior).
Error-tolerant parsing people still hit in production
Section titled “Error-tolerant parsing people still hit in production”The spec is deliberately forgiving: many errors do not stop parsing; they produce a DOM that may differ from what authors assumed.
Mis-nested formatting tags
Section titled “Mis-nested formatting tags”Markup such as <p>1<b>2<i>3</b>4</i>5</p> is repaired by the adoption agency algorithm and reconstruct the active formatting elements, which can insert extra elements so text lands under the right formatting context. The resulting DOM is valid per the spec but surprises anyone who expected strict nesting.
Unexpected markup inside tables
Section titled “Unexpected markup inside tables”A <b> directly inside <table> is not allowed in the table insertion mode; the parser foster-parents content, often placing nodes before the table or under tbody in non-obvious ways. Character data between table-related tags may batch through in table text and then be reprocessed under body rules with foster parenting—so whitespace-only runs behave differently from mixed text.
Scripts that move nodes during parse
Section titled “Scripts that move nodes during parse”If a script moves a node to another document while the parser still holds it on the stack of open elements, later tokens may insert siblings into a different document than the one being parsed; scripts only run when associated with the parser’s target document. The spec’s iframe example with document.getElementById and parent.document.body.appendChild illustrates why inline scripts during parse are order-sensitive.
Common mistakes when writing “valid-looking” HTML
Section titled “Common mistakes when writing “valid-looking” HTML”- Omitting
<!DOCTYPE html>and then debugging layout as if the page were in standards mode. - Using
/>on non-void HTML elements and expecting XML-style self-closing behavior (HTML uses the self-closing flag differently; non-void elements with/before>can be parse errors). - Unquoted attributes containing
/or>that swallow the rest of the tag. ©without;in an attribute value next to=or letters (stays literal in attributes).</table>-like sequences inside<script>or<style>without escaping.- Treating
<!--inside server templates as always safe in every element context. - Expecting
<![CDATA[in HTML body to protect markup (it does not in HTML namespace content).
How to check this on your site
Section titled “How to check this on your site”-
View the raw response bytes for the document and confirm the first non-whitespace construct is
<!DOCTYPE html>as defined in 13.1.1 The DOCTYPE. -
In browser devtools, inspect
document.doctype(name,publicId,systemId) anddocument.compatMode(CSS1Compatfor no-quirks vsBackCompatfor quirks) against the rules in initial insertion mode. -
For a suspicious fragment, compare the live DOM tree (elements, foster-parented nodes, extra formatting elements) with the non-normative repair examples in 13.2.10 Parsing HTML fragments (misnested tags, tables, scripts).
-
If you rewrite HTML on Cloudflare Workers, log
doctype.name,doctype.publicId, anddoctype.systemIdfrom HTMLRewriter and confirm they match the source preamble. -
You can check automatically in Answerwell (our tool): https://answerwell.org/workspace
Report an error or ask a question
Section titled “Report an error or ask a question”If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact sentence you are asking about so it can be corrected.