EthicsComputerCourses
Join training +91 90532 10052

HTML Tokenization & Tree Construction

HTML · Lesson 126 of 234 Advanced 11 min read Updated

By the end of this lesson you will be able to name the six token types, trace the tokenizer's states by hand, explain why <title> and <script> content is never parsed as tags, describe the stack of open elements and the list of active formatting elements, and run your own small tokenizer and tree builder.

What you should know first: Deep Understanding of HTML Parsing gave the overview of the pipeline and the 21 insertion modes, and DOM Tree & Node Relationships described the tree that comes out. Facts here follow the WHATWG HTML Living Standard, sections 13.2.4 to 13.2.6, checked in November 2026.

Six kinds of token

The tokenizer reads characters and emits tokens, one at a time. Each token goes straight to the tree builder before the next one is made. There are exactly six kinds:

TokenCarriesExample source
DOCTYPEname, public identifier, system identifier, force-quirks flag<!DOCTYPE html>
Start tagtag name, list of attributes, self-closing flag<input type="text" disabled/>
End tagtag name (attributes are a parse error)</p>
Commentdata<!-- price list -->
Characterone charactereach letter of Fees
End-of-filenothingthe end of the input

Two details matter:

  • The self-closing flag is set by />. On a void element such as <br/> it is simply allowed. On a normal element such as <div/> it is a parse error and is ignored, so the <div> stays open.
  • Tag and attribute names are lowercased as they are read, which is why HTML is case-insensitive.

The tokenizer's states

The tokenizer is a state machine with more than 80 states in the current standard. Think of a ticket checker on a train: normally he reads each ticket, but when a passenger says "group ticket", he switches state and counts heads until the group ends.

The states you meet most often:

StateWhat it is readingLeaves when it sees
DataNormal text< (to tag open) or & (to character reference)
Tag openJust after </ (end tag open), a letter (tag name), ! (comment or DOCTYPE)
Tag nameLetters of the namewhitespace, / or >
Before attribute nameSpace inside a taga letter starts an attribute name
Attribute nameLetters of the name=, whitespace, / or >
Before attribute valueJust after =", ' or any other character
Attribute value (double-quoted, single-quoted, unquoted)The valuethe closing quote, or whitespace or > when unquoted
Self-closing start tagJust after / in a tag> sets the self-closing flag
Character referenceAfter &the end of a name such as amp; or a number such as #8377;

A worked trace

Follow this input character by character. The left column is the input, the middle is the state before reading it, and the right says what happens.

Text
Input: <p class=fee>₹50 &amp; up</p>

char    state                          action
<       data                           switch to tag open
p       tag open                       create a start tag token, reconsume in tag name
p       tag name                       append "p" to the tag name
(space) tag name                       switch to before attribute name
c       before attribute name          start a new attribute, reconsume in attribute name
lass    attribute name                 append to the name: "class"
=       attribute name                 switch to before attribute value
f       before attribute value         reconsume in attribute value (unquoted)
fee     attribute value (unquoted)     append to the value
>       attribute value (unquoted)     emit start tag p {class="fee"}, switch to data
₹50␠    data                           emit four character tokens
&       data                           remember "data" as the return state, switch to character reference
a       character reference            reconsume in named character reference
amp;    named character reference      match "amp;" and emit "&", go back to data
␠up     data                           emit three character tokens
<       data                           switch to tag open
/       tag open                       switch to end tag open
p       end tag open                   create an end tag token, reconsume in tag name
>       tag name                       emit end tag p, switch to data
EOF     data                           emit end-of-file

"Reconsume" means reading the same character again in the new state. The tree builder joins the character tokens into one text node, "₹50 & up".

Text-only states: RCDATA, RAWTEXT and script data

Some elements hold text that must not be parsed as tags. When the tree builder inserts one of them, it switches the tokenizer into a text-only state:

StateUsed forTags inside?Character references decoded?
RCDATA<title>, <textarea>NoYes
RAWTEXT<style>, <xmp>, <iframe>, <noembed>, <noframes>, and <noscript> when scripting is onNoNo
Script data<script>NoNo, plus extra rules for <!-- inside scripts
PLAINTEXTthe obsolete <plaintext>No, and it never endsNo

In these states the only way out is the matching end tag, such as </title>. So <title>a<b>c</title> gives the text a<b>c, not a bold element, and <textarea> shows &amp; as &.

This has a famous consequence. The script data state ends at the first </script it sees, even inside a JavaScript string:

HTML
<script>
  const html = "</script><p>Oops</p>";   // the script element ends here
</script>

The script ends inside the string, so the JavaScript fails and <p>Oops</p> becomes page content. Write "<\/script>" instead. When you put JSON from a server inside a <script>, escape < as \u003c for the same reason. Void Elements & Raw Text Elements looks at these elements from the author's side.

Live coding: a toy tokenizer

Now build a tokenizer for a small part of HTML. It is simplified on purpose:

  • it handles tags, attributes in all three quoting styles, the self-closing flag, comments and text;
  • it does not decode character references and skips DOCTYPE details;
  • it switches to RCDATA, RAWTEXT and script data by itself, a job the real tree builder does.

Step 1: keep one variable, state, and a switch with one case per state.

Step 2: for each character, decide what to append and which state comes next. Record every state change in a trace.

Step 3: compare the result with the real parser, using DOMParser.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Toy tokenizer</title>
  <style>
    body { font-family: sans-serif; padding: 1rem; }
    textarea { width: 100%; height: 3.5rem; font-family: monospace; }
    .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(18rem, 1fr)); gap: 8px; }
    pre { background: #f4f4f4; padding: 8px; margin: 0; overflow-x: auto; font-size: 13px; }
  </style>
</head>
<body>
  <h1>Toy HTML tokenizer (simplified)</h1>
  <label for="src">Markup:</label>
  <textarea id="src"><p class=fee>Fees <b>due</b></p><title>a<b>c</title></textarea>
  <p><button id="go">Tokenize</button></p>
  <div class="grid">
    <div><h2>Tokens</h2><pre id="tokens"></pre></div>
    <div><h2>State changes</h2><pre id="trace"></pre></div>
  </div>
  <h2>The real parser built</h2>
  <pre id="real"></pre>

  <script>
    // SIMPLIFIED: no character references, no DOCTYPE details, comments only as <!--...-->,
    // and the tokenizer itself switches to the text-only states (the real tree builder does that).
    function tokenize(input) {
      const tokens = [], trace = [];
      let state = "data", text = "", tag = null, attr = null, endTag = "", i = 0;
      const textOnly = { script: "script data", style: "RAWTEXT", title: "RCDATA", textarea: "RCDATA" };

      const go = (next, ch) => { trace.push(JSON.stringify(ch).padEnd(6) + state + " -> " + next); state = next; };
      const flushText = () => { if (text) { tokens.push({ type: "character", data: text }); text = ""; } };
      const finishAttr = () => { if (attr) { tag.attrs.push(attr); attr = null; } };
      const emitTag = (ch) => {
        finishAttr();
        flushText();
        tokens.push(tag);
        if (tag.type === "start tag" && textOnly[tag.name]) {
          endTag = "</" + tag.name;
          go(textOnly[tag.name], ch);
        } else {
          go("data", ch);
        }
        tag = null;
      };

      while (i <= input.length) {
        const ch = i < input.length ? input[i] : "EOF";
        if (ch === "EOF" && (state === "data" || state in { "script data": 1, RAWTEXT: 1, RCDATA: 1 })) {
          flushText();
          tokens.push({ type: "end-of-file" });
          break;
        }
        switch (state) {
          case "data":
            if (ch === "<") go("tag open", ch); else text += ch;
            break;
          case "script data": case "RAWTEXT": case "RCDATA":
            // Only the matching end tag can leave these states.
            if (input.slice(i, i + endTag.length).toLowerCase() === endTag) go("tag open", ch);
            else text += ch;
            break;
          case "tag open":
            if (ch === "/") go("end tag open", ch);
            else if (/[a-z]/i.test(ch)) { tag = { type: "start tag", name: "", attrs: [], selfClosing: false }; go("tag name", ch); continue; }
            else if (input.startsWith("!--", i)) {          // shortcut for comments
              const end = input.indexOf("-->", i);
              const stop = end === -1 ? input.length : end;
              flushText();
              tokens.push({ type: "comment", data: input.slice(i + 3, stop) });
              go("data", "<!--");
              i = stop + 2;
            }
            else { text += "<"; go("data", ch); continue; }  // a lone "<" is just text
            break;
          case "end tag open":
            if (/[a-z]/i.test(ch)) { tag = { type: "end tag", name: "", attrs: [], selfClosing: false }; go("tag name", ch); continue; }
            go("data", ch);
            break;
          case "tag name":
            if (/\s/.test(ch)) go("before attribute name", ch);
            else if (ch === "/") go("self-closing start tag", ch);
            else if (ch === ">") emitTag(ch);
            else if (ch !== "EOF") tag.name += ch.toLowerCase();
            break;
          case "before attribute name":
            if (/\s/.test(ch)) break;
            if (ch === "/") go("self-closing start tag", ch);
            else if (ch === ">") emitTag(ch);
            else if (ch !== "EOF") { attr = { name: "", value: "" }; go("attribute name", ch); continue; }
            break;
          case "attribute name":
            if (ch === "=") go("before attribute value", ch);
            else if (/\s/.test(ch)) { finishAttr(); go("before attribute name", ch); }
            else if (ch === "/") { finishAttr(); go("self-closing start tag", ch); }
            else if (ch === ">") emitTag(ch);
            else if (ch !== "EOF") attr.name += ch.toLowerCase();
            break;
          case "before attribute value":
            if (ch === '"') go("attribute value (double-quoted)", ch);
            else if (ch === "'") go("attribute value (single-quoted)", ch);
            else { go("attribute value (unquoted)", ch); continue; }
            break;
          case "attribute value (double-quoted)":
          case "attribute value (single-quoted)":
            if (ch === (state.includes("double") ? '"' : "'")) { finishAttr(); go("before attribute name", ch); }
            else if (ch !== "EOF") attr.value += ch;
            break;
          case "attribute value (unquoted)":
            if (/\s/.test(ch)) { finishAttr(); go("before attribute name", ch); }
            else if (ch === ">") emitTag(ch);
            else if (ch !== "EOF") attr.value += ch;
            break;
          case "self-closing start tag":
            if (ch === ">") { tag.selfClosing = true; emitTag(ch); }
            else { go("before attribute name", ch); continue; }
            break;
        }
        if (ch === "EOF") { tokens.push({ type: "end-of-file" }); break; }  // file ended inside a tag
        i++;
      }
      return { tokens, trace };
    }

    function describe(t) {
      if (t.type === "start tag" || t.type === "end tag") {
        const attrs = t.attrs.map((a) => " " + a.name + '="' + a.value + '"').join("");
        return t.type.padEnd(10) + " " + t.name + attrs + (t.selfClosing ? "  (self-closing flag)" : "");
      }
      if (t.type === "end-of-file") return "end-of-file";
      return t.type.padEnd(10) + " " + JSON.stringify(t.data);
    }

    function run() {
      const markup = document.querySelector("#src").value;
      const { tokens, trace } = tokenize(markup);
      document.querySelector("#tokens").textContent = tokens.map(describe).join("\n");
      document.querySelector("#trace").textContent = trace.join("\n");
      const doc = new DOMParser().parseFromString(markup, "text/html");
      document.querySelector("#real").textContent =
        "head: " + doc.head.innerHTML + "\nbody: " + doc.body.innerHTML;
    }
    document.querySelector("#go").addEventListener("click", run);
    run();
  </script>
</body>
</html>

The default input gives these tokens:

Output
start tag  p class="fee"
character  "Fees "
start tag  b
character  "due"
end tag    b
end tag    p
start tag  title
character  "a<b>c"
end tag    title
end-of-file

The trace shows tag name -> RCDATA after <title>, which is why <b> inside it stayed text. The real parser agrees: it shows <title>a&lt;b&gt;c</title>, with the angle brackets escaped as text. Our toy emits one character token per run of text to keep the output short; the standard emits one per character. Try <br/>, <img src=a.png alt='Pune station'> and an unclosed <p class="x to see the self-closing flag, single quotes and a token abandoned at the end of the file.

Tree construction

The tree builder receives tokens and uses four main pieces of state.

The insertion mode. It decides which set of rules handles the next token. "In body" is the biggest; "in table", "in row" and "in cell" handle tables; "text" is used inside <title> or <script>. Some modes borrow another mode's rules, for example "in table" handles a <script> "using the rules for the in head insertion mode".

The stack of open elements. Like a stack of plates, new elements go on top and closing removes them. The top is the current node, where new nodes are inserted. When the builder sees </ul>, it pops elements until the ul comes off, which also closes any li still open.

The list of active formatting elements. Formatting elements are a, b, big, code, em, font, i, nobr, s, small, strike, strong, tt and u. The list remembers which are still "in force", so they can be reconstructed after a block closes them. Markers are added when entering td, th, caption, template, object, applet and marquee, so formatting does not leak into a table cell. The list keeps at most three identical entries (the standard calls this the Noah's Ark clause).

Text
Input:  <p><b>Bold<p>Still bold
Result: <p><b>Bold</b></p><p><b>Still bold</b></p>

The second <p> closes the first paragraph and pops the b. But b is still in the list of active formatting elements, so before inserting "Still bold" the builder makes a new b.

Element pointers and flags, such as the head element, any open form, and a "frameset-ok" flag.

Two more repairs use this state. Misnested tags such as <b>Fees <i>due</b> now</i> go through the adoption agency algorithm, which gives <b>Fees <i>due</i></b><i> now</i>. Text or elements placed directly inside a <table> are foster parented: inserted just before the table instead of inside it. HTML Error Recovery Mechanism studies these algorithms step by step.

Step 4: a toy tree builder

This second toy takes a list of tokens and builds a tree with a stack of open elements. It follows only a few "in body" rules: void elements are never pushed, a block start tag closes an open <p>, a new <li> closes an open <li>, and an unmatched </p> creates an empty paragraph. It prints the stack after each token, then compares its result with the real parser.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Toy tree builder</title>
  <style>
    body { font-family: sans-serif; padding: 1rem; }
    input { width: 100%; font-family: monospace; }
    pre { background: #f4f4f4; padding: 8px; overflow-x: auto; font-size: 13px; }
  </style>
</head>
<body>
  <h1>Toy tree builder with a stack of open elements (simplified)</h1>
  <label for="tokens">Tokens, separated by spaces (use _ for a space inside text):</label>
  <input id="tokens" value="<div> <p> Fees_due <ul> <li> Term_1 <li> Term_2 </ul> </p> <br> </div>">
  <p><button id="go">Build</button></p>
  <pre id="out"></pre>

  <script>
    // SIMPLIFIED rules, a tiny part of the "in body" insertion mode:
    // 1. void elements are inserted but never pushed on the stack;
    // 2. a block start tag closes an open <p>; a new <li> closes an open <li>;
    // 3. an end tag pops elements until its match; with no match it is ignored,
    //    except </p>, which creates an empty paragraph.
    const VOID = ["br", "img", "input", "hr", "meta", "link"];
    const CLOSES_P = ["p", "div", "ul", "ol", "table", "h1", "h2", "h3", "section"];

    function build(list) {
      const root = document.createElement("div");
      const stack = [root];                       // the stack of open elements
      const current = () => stack[stack.length - 1];
      const has = (name) => stack.some((el) => el.localName === name);
      const popUntil = (name) => { while (stack.length > 1 && stack.pop().localName !== name) {} };
      const log = [];

      for (const token of list) {
        let note = "";
        if (token.startsWith("</")) {
          const name = token.slice(2, -1);
          if (has(name)) popUntil(name);
          else if (name === "p") { current().append(document.createElement("p")); note = "  (no open p: empty <p> created)"; }
          else note = "  (no match: ignored)";
        } else if (token.startsWith("<")) {
          const name = token.slice(1, -1);
          if (CLOSES_P.includes(name) && has("p")) { popUntil("p"); note = "  (closed the open p)"; }
          if (name === "li" && has("li")) { popUntil("li"); note = "  (closed the open li)"; }
          const el = document.createElement(name);
          current().append(el);
          if (!VOID.includes(name)) stack.push(el);
        } else {
          current().append(token.replaceAll("_", " "));
        }
        log.push(token.padEnd(10) + "stack: " + stack.slice(1).map((el) => el.localName).join(" > ") + note);
      }
      return { html: root.innerHTML, log };
    }

    function run() {
      const list = document.querySelector("#tokens").value.trim().split(/\s+/);
      const { html, log } = build(list);
      const real = new DOMParser().parseFromString(list.join("").replaceAll("_", " "), "text/html").body.innerHTML;
      document.querySelector("#out").textContent =
        log.join("\n") + "\n\nToy result:  " + html + "\nReal parser: " + real +
        "\nSame? " + (html === real);
    }
    document.querySelector("#go").addEventListener("click", run);
    run();
  </script>
</body>
</html>
Output
<div>     stack: div
<p>       stack: div > p
Fees_due  stack: div > p
<ul>      stack: div > ul  (closed the open p)
<li>      stack: div > ul > li
Term_1    stack: div > ul > li
<li>      stack: div > ul > li  (closed the open li)
Term_2    stack: div > ul > li
</ul>     stack: div
</p>      stack: div  (no open p: empty <p> created)
<br>      stack: div
</div>    stack: 

Toy result:  <div><p>Fees due</p><ul><li>Term 1</li><li>Term 2</li></ul><p></p><br></div>
Real parser: <div><p>Fees due</p><ul><li>Term 1</li><li>Term 2</li></ul><p></p><br></div>
Same? true

Now try <p> <b> Bold <p> Still_bold. The toy prints Same? false, because it has no list of active formatting elements and cannot reconstruct the b. That missing piece is exactly what the real algorithm adds.

Common mistakes

  • Writing </script> inside a script string. It ends the element; write <\/script>.
  • Expecting <div/> to close the div. The self-closing flag is ignored on non-void elements.
  • Putting markup in <title> or <textarea>. It is shown as text, because these use RCDATA.
  • Parsing HTML with regular expressions. Text-only states, implied end tags and repairs make regexes unreliable; use DOMParser.
  • Thinking end tags close only their own element. </ul> pops everything above the ul on the stack.

Interview questions

1. What token types does the HTML tokenizer produce?

DOCTYPE, start tag, end tag, comment, character and end-of-file. Start and end tags carry a name, attributes and a self-closing flag; DOCTYPE tokens carry a name, public and system identifiers and a force-quirks flag.

2. Why is <b> inside <title> shown as text?

When the tree builder inserts a <title>, it switches the tokenizer to the RCDATA state. In RCDATA, < does not start a tag; only </title> ends the state. Character references are still decoded.

3. What is the difference between RCDATA and RAWTEXT?

Both treat everything as text until the matching end tag. RCDATA, used by <title> and <textarea>, decodes character references such as &amp;. RAWTEXT, used by <style> and similar elements, does not.

4. What is the stack of open elements?

It is the list of elements that have been opened but not yet closed, with the current node on top. New nodes are inserted into the current node, and end tags pop elements off the stack, which also closes any elements opened inside them.

5. What does the list of active formatting elements do?

It records formatting elements such as b and a that are still in force, so the parser can reconstruct them after a block element closes them. It is also used by the adoption agency algorithm to repair misnested tags, and markers stop formatting from leaking into table cells.

Key points

  • The tokenizer emits six token types and hands each one to the tree builder immediately.
  • It is a state machine with more than 80 states; data, tag open, tag name and the attribute states do most of the work.
  • The tree builder switches the tokenizer into RCDATA, RAWTEXT or script data for elements whose content is text.
  • </script inside a script ends it, even inside a JavaScript string.
  • Tree construction uses the insertion mode, the stack of open elements, the list of active formatting elements and element pointers.
  • Reconstruction, the adoption agency algorithm and foster parenting all rely on that state.

Exercise

Ananya runs a recipe site in Lucknow. Trace by hand, as in the worked example, the tokens produced by <textarea name=note>Use &lt;b&gt; for bold</textarea>, naming the state after each important character. Then predict the DOM for <p><i>Tip:<p>Add kesar last and check both answers with the two toy pages and DOMParser.

Show solution

Tokens: start tag textarea with name="note" (tag open, tag name, before attribute name, attribute name, before attribute value, attribute value unquoted, then >). The tree builder switches the tokenizer to RCDATA. In RCDATA, &lt; and &gt; pass through the character reference state and become < and >, so the characters are Use <b> for bold. </textarea> goes through tag open, end tag open and tag name and emits the end tag; then end-of-file.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Check</title>
</head>
<body>
  <pre id="out"></pre>
  <script>
    const parse = (s) => new DOMParser().parseFromString(s, "text/html").body;
    const a = parse("<textarea name=note>Use &lt;b&gt; for bold</textarea>");
    const b = parse("<p><i>Tip:<p>Add kesar last");
    document.querySelector("#out").textContent =
      JSON.stringify(a.querySelector("textarea").value) + "\n" + b.innerHTML;
  </script>
</body>
</html>

The output is "Use <b> for bold" and <p><i>Tip:</i></p><p><i>Add kesar last</i></p>: the i is reconstructed in the second paragraph from the list of active formatting elements.

Quick Quiz

1. Which tokenizer state is used for the content of <textarea>?

2. What happens to the self-closing flag on <div/>?

3. Which structure lets the parser recreate a <b> after a new paragraph starts?

4. Why must a string containing </script> be written as "<\/script>" inside a script?

Learn HTML with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call