HTML (Document Structure & the DOM)

HTML is the markup language that describes web page structure and semantics; browsers parse HTML into a DOM tree and combine it with stylesheets, scripts, and other assets to build the page. The live DOM can differ from the raw HTML source and can be mutated by JavaScript after loading.

Second-Draft Verification Note (2026-10-15): This article is the second draft of the HeLuoXu tutorial series, revised against official specifications and documentation. Legacy experiment logs are labeled separately as "First-Draft Archived Output" and do not represent a fresh re-run on Windows in this batch; see the batch verification records for current environment details. "Xinghe Notes", accounts, orders, prices, and policies in the examples are fictional teaching data.

One-Line Definition

HTML is the markup language that describes web page structure and semantics; browsers parse HTML into a DOM tree and combine it with stylesheets, scripts, and other assets to build the page. The live DOM can differ from the raw HTML source and can be mutated by JavaScript after loading.

Why It Matters

  • Web pages are one of the most common data sources for RAG; without understanding HTML structure, extracted text easily pulls in navigation bars, ads, and inline scripts, or loses the row-and-column relationships of tables (k4.rag.chunking).
  • Frontend frameworks (React, Vue) ultimately render down to DOM nodes; understanding the DOM is a prerequisite for understanding how they work.
  • Inserting unescaped LLM output into a web page is a frequent source of XSS vulnerabilities, while hidden text inside scraped web pages is a common vector for indirect prompt injection (k6.sec.prompt-injection).

How It Works / Diagram

HTML Living Standard (WHATWG): https://html.spec.whatwg.org/; Parsing Algorithm (including error-tolerance rules): https://html.spec.whatwg.org/multipage/parsing.html; MDN HTML Guide: https://developer.mozilla.org/zh-CN/docs/Learn/HTML

Figure 1
Semantic Tag Meaning Significance for RAG / Accessibility
<main> Primary page content First-choice target scope for body text extraction
<nav>, <footer>, <aside> Navigation, footer, sidebar Usually stripped before indexing
<article>, <section> Self-contained article, thematic section Natural boundaries for document chunking
<h1>–<h6> Heading hierarchy Preserved as section metadata on chunks
<img alt> Image alternative text Relied upon by screen readers and text retrieval

Scope Boundaries & Verification Points

Tags like main and article are useful heuristics for extracting body content, but they do not guarantee accurate authoring and are never a trust or security boundary. textContent returns the text of the selected subtree — including text inside script/style elements and visually hidden elements, while excluding HTML comments — and it flattens table structure without reflecting visual visibility. Missing alt attributes are an audit signal, though purely decorative images should use alt="" rather than verbose descriptions. Finally, jsdom is not a full browser rendering engine; inspecting an event handler attribute confirms the DOM node carries it, not that the script executed in a real browser during the test.

Primary references verified in this batch (2026-10-15):

Runnable Example

Uses Node.js and jsdom to parse a sample HTML document and inspect the resulting DOM structure without running a browser layout engine. The sample markup intentionally omits several closing tags and an alt attribute to observe parser recovery and audit checks.

File: examples/web/page.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <title>Xinghe Notes · Refund Policy</title>
  <meta name="description" content="7-day no-questions-asked refund guide">
</head>
<body>
  <nav><a href="/">Home</a> | <a href="/help">Help Center</a></nav>
  <main>
    <article>
      <h1>Refund Policy</h1>
      <p>No-questions-asked refunds are available <strong>within 7 days</strong> of purchase.
      <p>Membership fees are prorated by remaining days.
      <img src="refund.png">
      <table><tr><th>Channel</th><th>Processing Time</th></tr><tr><td>WeChat Pay</td><td>1–3 days</td></tr></table>
    </article>
  </main>
  <footer>© 2026 Xinghe Notes (Fictional)</footer>
  <script>console.log("analytics tracker")</script>
</body>
</html>
// File: examples/web/15_html.mjs
// Parse the page with jsdom (an HTML-standard-compliant parser): DOM tree, error recovery,
// accessibility checks, RAG body extraction, and innerHTML vs. textContent.
import { JSDOM } from "jsdom";
import fs from "fs";
const html = fs.readFileSync(new URL("./page.html", import.meta.url), "utf8");
const dom = new JSDOM(html); const doc = dom.window.document;

console.log("1. DOM tree (elements only, indentation shows depth):");
(function walk(n, d) { if (d > 4) return; for (const c of n.children) { console.log("  ".repeat(d + 1) + c.tagName.toLowerCase()); walk(c, d + 1); } })(doc.documentElement, 0);

console.log("\n2. Error recovery: neither <p> in source had a closing </p>, auto-closed by parser -> <p> count =", doc.querySelectorAll("p").length);
console.log("   First <p> innerHTML:", doc.querySelector("p").innerHTML.trim());
console.log("   Source <table> had no <tbody>, after parsing:", doc.querySelector("table").firstElementChild.tagName.toLowerCase());

console.log("\n3. Metadata: title =", doc.title, "| lang =", doc.documentElement.lang, "| description =", doc.querySelector('meta[name=description]').content);
const noAlt = [...doc.querySelectorAll("img")].filter(i => !i.hasAttribute("alt")).map(i => i.getAttribute("src"));
console.log("4. Accessibility check: images missing alt =", noAlt, "| heading levels =", [...doc.querySelectorAll("h1,h2,h3")].map(h => h.tagName));

const main = doc.querySelector("main").cloneNode(true);
const text = main.textContent.replace(/\s+/g, " ").trim();
const all = doc.body.textContent.replace(/\s+/g, " ").trim();
console.log("\n5. Extracting main text for RAG: full body text", all.length, "chars (includes nav/footer/script); <main> only:", text.length, "chars");
console.log("   ", text);

const evil = '<img src=x onerror="window.__hacked=1">';
const box1 = doc.createElement("div"); box1.textContent = evil;
console.log("\n6. Assigning via textContent:", box1.innerHTML, "-> rendered safely as literal text");
const box2 = doc.createElement("div"); box2.innerHTML = evil;
console.log("   Assigning via innerHTML: child element =", box2.firstElementChild.tagName, "has onerror attribute =", box2.firstElementChild.hasAttribute("onerror"), "-> executes script in a real browser");

First-Draft Archived Output

The following log is preserved from the first draft's original environment and is not a re-run from this batch. Code adjustments in the second draft may produce different output; refer to the batch verification record for actual re-run status.

v20.19.2
jsdom 24.1.3
1. DOM tree (elements only, indentation shows depth):
  head
    meta
    title
    meta
  body
    nav
      a
      a
    main
      article
        h1
        p
          strong
        p
          img
        table
          tbody
    footer
    script

2. Error recovery: neither <p> in source had a closing </p>, auto-closed by parser -> <p> count = 2
   First <p> innerHTML: No-questions-asked refunds are available <strong>within 7 days</strong> of purchase.
   Source <table> had no <tbody>, after parsing: tbody

3. Metadata: title = Xinghe Notes · Refund Policy | lang = zh-CN | description = 7-day no-questions-asked refund guide
4. Accessibility check: images missing alt = [ 'refund.png' ] | heading levels = [ 'H1' ]

5. Extracting main text for RAG: full body text 93 chars (includes nav/footer/script); <main> only: 47 chars
    Refund Policy No-questions-asked refunds are available within 7 days of purchase. Membership fees are prorated by remaining days. ChannelProcessing TimeWeChat Pay1–3 days

6. Assigning via textContent: &lt;img src=x onerror="window.__hacked=1"&gt; -> rendered safely as literal text
   Assigning via innerHTML: child element = IMG has onerror attribute = true -> executes script in a real browser
  • 1 & 2. Parser Error Recovery: Neither <p> tag was closed in the raw HTML source, yet the parser automatically closed both per the HTML specification, producing 2 <p> elements. The <img> landed inside the second <p>, while the opening <table> tag implicitly closed that <p>, making the table a direct child of <article>; the parser also inserted an implicit <tbody> inside <table>. Raw HTML source != the browser's DOM tree — always write CSS/DOM selectors against the parsed DOM structure.
  • 4. A simple accessibility check flags that refund.png is missing an alt attribute.
  • 5. In the original Chinese text run, full-page extraction yielded 93 characters while scoping to <main> reduced it to 47 characters, stripping navigation, footer, and script text. Notice, however, that textContent squashed the table cells into ChannelProcessing TimeWeChat Pay1–3 days — losing the row-and-column structure. During RAG ingestion, HTML tables should be converted separately into Markdown tables or column: value pairs.
  • 6. Assigning via textContent escapes <img ... onerror> into harmless text, whereas assigning via innerHTML instantiates a live IMG element carrying an onerror handler that would execute JavaScript in a browser (jsdom does not execute scripts by default, so we inspect the attribute directly).

Self-Test

Question: Does extracting only main.textContent eliminate all hidden prompt-injection risks and table-formatting issues?

Reference Answer: No. The <main> element can still contain visually hidden or malicious text, and textContent flattens table column relationships. You should extract content using structure-aware parsers and always treat external web content as untrusted data.

Common Pitfalls

  • "If my HTML has syntax errors, the browser will throw an error": Browsers follow standardized HTML error-recovery rules rather than halting like a strict XML parser; the page will still render, though the resulting DOM may differ from what you intended. Validate markup with the W3C Validator (https://validator.w3.org/).
  • "Using <div> everywhere is fine": Visually it may look identical, but screen readers, search engines, and content-extraction tools rely heavily on semantic tags.
  • "Regular expressions are enough to parse HTML": Nested tags, implicit closing rules, comments, and > inside attributes break regex parsers quickly; always use a real HTML parser (BeautifulSoup, lxml, jsdom, etc.).
  • "Invisible text on a page doesn't matter": Whether display:none elements, white-on-white text, or HTML comments are ingested depends on your extraction layer; visual rendering, DOM text, and raw HTML source are three distinct layers — and that gap is a frequent hiding place for indirect prompt injection.

Connection to AI Development

  • Before indexing web pages for RAG: target <main>/<article>, strip <script>/<style>/<nav>, format tables explicitly, and preserve heading hierarchies as chunk metadata. Common libraries include trafilatura, readability, and BeautifulSoup.
  • When rendering LLM outputs in a frontend: use textContent, or sanitize rendered Markdown HTML with a dedicated sanitizer such as DOMPurify before insertion (https://github.com/cure53/DOMPurify).
  • When building a web-browsing Agent, feeding it only visible text plus the accessibility tree helps reduce exposure to hidden prompt-injection payloads.

Further Reading

Unverified Scope

  • Did not perform a full WCAG accessibility audit, real browser XSS execution test, or prompt-injection benchmark; visibility-based extraction alone is not a complete defense against prompt injection.

Current Example Execution Scope

2026-10-15: Passed. Executed locally with Node.js and locked dependencies; DOM parsing demonstrated via jsdom without a real browser layout engine.

View current batch log.

"First-Draft Archived Output" retains the original log text and is not newly generated by the revised second-draft code; read its conclusions alongside the second-draft revisions and scope boundaries.

Companion Code & Verification Materials

Back to Foundations Back to Learn →Back to top ↑
On this page
Tutorial diagram100%
Tutorial diagram