๐Ÿ’ฌ Chapter 10: HTML Comments & Special Characters

HTML Comment Syntax

Understanding the WHATWG comment tokenizer, parse rules, invalid nested hyphens, and DOM `CommentNode` mechanics.

LEARNING OBJECTIVES โŒต
  • Understand the exact lexical anatomy of HTML comments (<!-- and -->) according to the WHATWG specification.
  • Trace how the browser's HTML tokenizer transitions through states when processing comment tokens.
  • Explain why consecutive hyphens (--) or closing delimiters inside comments trigger parser errors.
  • Inspect, query, and manipulate Comment nodes in the Document Object Model (DOM) using JavaScript.
๐ŸŽฌ INTERACTIVE VISUAL PIPELINE Core Architecture Simulation
๐ŸŒ
1. Input
Directives & Tags
โš™๏ธ
2. Parse
Tokenizer & AST
๐ŸŒณ
3. Layout
Box Model & Flow
๐ŸŽจ
4. Render
GPU Paint & Composite
PHASE 1: INPUT & DIRECTIVES
Browser receives declarative markup stream, parsing tag tokens and initializing component state.

๐Ÿ“– The Mental Model & Story (Intuitive Foundation)

Imagine an architect sending a set of construction blueprints to a building contractor. Across the blueprints, the architect uses a special red wax pencil to write private annotations: "Remember to insulate behind this drywall", "Check local seismic codes before pouring foundation", or "Pending city inspection permit".

When the construction crew pours concrete and builds walls, they follow the black structural ink, completely ignoring the red wax pencil marks. The building occupants never see the architect's private notes on the finished walls. However, if an engineer inspects the original blueprints rolled up inside the planning office, every single red note is still intact and legible.

       +-------------------------------------------------------+
       |                  HTML SOURCE DOCUMENT                 |
       |  <header>                                             |
       |    <!-- ARCHITECT NOTE: Red Wax Pencil (Comment) -->  |
       |    <h1>Acme Global Corp</h1>                          |
       |  </header>                                            |
       +-------------------------------------------------------+
                                  |
                                  | Browser Parsing
                                  v
  +--------------------------------+--------------------------------+
  |       RENDERED PIXELS          |            DOM TREE            |
  |     (User Facing Canvas)       |    (In-Memory Object Graph)    |
  |                                |                                |
  |   Acme Global Corp             |    [Element: header]           |
  |   (Comment produces NO pixels) |      |-- [CommentNode: "ARCH.."]|
  |                                |      \-- [Element: h1]         |
  +--------------------------------+--------------------------------+

In HTML, <!-- and --> are your red wax pencil. Anything wrapped inside them is ignored by the browser's layout and paint subsystems. But crucially: comments are not erased from existence. The browser parses them into actual nodes in the memory tree (the DOM), where they can be inspected, queried, and read by anyone who inspects the page source.


Technical Deep Dive & Specifications

The Anatomy of an HTML Comment

An HTML comment consists of three components:

  1. Comment Start Sequence: Exactly <!-- (Less-than, exclamation mark, hyphen, hyphen).
  2. Comment Data: Zero or more characters representing the text payload.
  3. Comment End Sequence: Exactly --> (Hyphen, hyphen, greater-than).
<!-- This is comment data -->

The WHATWG HTML Tokenizer State Machine

The HTML5 living standard specifies a deterministic finite state machine (FSM) for parsing markup. When the tokenizer encounters <, it evaluates the subsequent characters:

  [ Data State ]
        |  encounter '<'
        v
  [ Tag Open State ]
        |  encounter '!'
        v
  [ Markup Declaration Open State ]
        |  encounter '--'
        v
  [ Comment Start State ]
        |  any character (e.g. 'A')
        v
  [ Comment State ] <----------- (consumes comment characters)
        |  encounter '-'
        v
  [ Comment End Dash State ]
        |  encounter '-'
        v
  [ Comment End State ]
        |  encounter '>'
        v
  [ Data State ] (Emits Comment Token to Tree Builder)

WHATWG Syntax Rules & Prohibited Patterns

According to the WHATWG specification, valid HTML comments must adhere to strict lexical constraints:

Pattern / Rule Status Technical Explanation
<!-- Valid Comment --> โœ… Valid Clean opening, text payload, clean closing.
<!--> โŒ Parse Error Abrupt closing tag error (abrupt-closing-of-empty-comment).
<!---> โŒ Parse Error Missing required closing hyphen (abrupt-closing-of-empty-comment).
<!-- A -- B --> โŒ Parse Error Nested -- is an error (nested-comment parse error). In legacy SGML, -- acted as a toggle delimiter.
<!-- Comment ---> โŒ Parse Error Extra trailing hyphen before closing delimiter (incorrectly-closed-comment).
<!--<!DOCTYPE html>--> โœ… Valid Markup characters inside comments are treated as raw character data.

[!NOTE] Even though modern browsers recover gracefully from parse errors (error-recovery mode), invalid comment syntax can cause unpredictable DOM structures in older tools, XML/XHTML parsers, or strict linters.

Comments in the DOM: The Comment Interface

A common misconception is that comments disappear during parsing. In reality, the browser's Tree Builder constructs a CommentNode for every comment encountered.

In the Web IDL hierarchy:

  EventTarget
      โ””โ”€โ”€ Node (nodeType === 8 for Node.COMMENT_NODE)
            โ””โ”€โ”€ CharacterData
                  โ”œโ”€โ”€ Text (nodeType === 3)
                  โ”œโ”€โ”€ CDATASection (nodeType === 4)
                  โ”œโ”€โ”€ ProcessingInstruction (nodeType === 7)
                  โ””โ”€โ”€ Comment (nodeType === 8)

Inspecting and Querying Comments via JavaScript:

// Accessing child nodes of an element
const header = document.querySelector('header');

header.childNodes.forEach(node => {
  if (node.nodeType === Node.COMMENT_NODE) {
    console.log("Found comment:", node.nodeValue); // or node.data
  }
});

// Creating a comment dynamically
const newComment = document.createComment("Generated dynamically by script");
document.body.appendChild(newComment);

SYS: ACTIVE
HULL: 98%
CORE: STABLE
NET: ONLINE
HTML STARSHIP CODE TERMINAL example.html
LIVE RENDER & DIAGNOSTICS CORE TEMP: 45ยฐC
INSPECTING DOM: VALID
TAGS: SCANNING...

๐Ÿ’ป Interactive Code Playground

Starter Code

Line-by-Line Code Breakdown

  • Line 8โ€“10 (<!-- === ... HERO SECTION ... === -->): Structured banner comment marking the start of a major functional UI module.
  • Line 11 (<section id="hero">): The semantic DOM container element.
  • Line 14 (<!-- <button ...> ... -->): Temporarily commented-out (disabled) HTML markup with an explanatory note. The browser does not render this button.
  • Line 26โ€“36 (<script>...childNodes.forEach...</script>): JavaScript traversing the heroSection child nodes. When it encounters node.nodeType === 8 (Node.COMMENT_NODE), it accesses node.data and logs it to the UI.

Expected Browser Render Output

(Notice that the secondary button is not rendered visually, but its comment node exists in the DOM and is extracted via script).


SYS: ACTIVE
HULL: 98%
CORE: STABLE
NET: ONLINE
HTML STARSHIP CODE TERMINAL playground.html
LIVE RENDER & DIAGNOSTICS CORE TEMP: 45ยฐC
INSPECTING DOM: VALID
TAGS: SCANNING...
Supercharge Your Workflow
The developer platform built for high-performance teams.
[Get Started Free]

DOM Comment Inspector Log:
โ€ข Index [1] (Node.COMMENT_NODE): "========================================================"
โ€ข Index [3] (Node.COMMENT_NODE): "HERO SECTION: Primary user conversion banner"
โ€ข Index [5] (Node.COMMENT_NODE): "========================================================"
โ€ข Index [9] (Node.COMMENT_NODE): "<button class="btn-secondary">Learn More</button> (Temporarily disabled for Q3 launch)"

๐Ÿ‹๏ธ Hands-On Exercise

๐ŸŽฏ The Challenge: DOM Comment Node Extractor & Validator

Instructions:

  1. Create an HTML document with a main container <main id="app">.
  2. Inside #app, write at least three different valid HTML comments:
    • A section header comment.
    • An inline explanatory note.
    • A disabled paragraph block.
  3. Write an inline <script> that uses TreeWalker (document.createTreeWalker) with NodeFilter.SHOW_COMMENT to locate all comments inside #app.
  4. Output the total comment count and their exact text contents into an unordered list <ul id="audit-results">.

๐Ÿ Starter Code Sandbox

SYS: ACTIVE
HULL: 98%
CORE: STABLE
NET: ONLINE
STARTER CODE SANDBOX exercise.html
LIVE RENDER & DIAGNOSTICS CORE TEMP: 45ยฐC
INSPECTING DOM: VALID
TAGS: SCANNING...

โš ๏ธ Common Pitfalls

  1. Placing Double Hyphens Inside Comments (<!-- Foo -- Bar -->): The sequence -- inside an HTML comment triggers a parser error under the WHATWG specification and can cause premature closing in XML/XHTML or third-party tools.
  2. Using C/JavaScript Style Comments (// or /* */) in HTML: Browsers do not recognize // or /* */ in standard HTML body text. Writing // TODO: fix this inside a <div> will render // TODO: fix this as visible text on the screen.
  3. Assuming Comments are Private: Never put sensitive logic, passwords, API tokens, internal URLs, or personal data inside HTML comments. Anyone can view them via "View Source" or DevTools.

๐Ÿ’ก Pro Tips

  1. Automate Stripping with Minifiers in Production: Use build tools (such as HTMLNano, Vite, esbuild, or HtmlWebpackPlugin) configured with removeComments: true to strip developer comments from production bundles, saving network bytes.
  2. Leverage nodeType === 8 for Non-Intrusive Markers: Libraries like React, Vue, and Knockout historically use DOM comment nodes as hydration boundaries or dynamic component placeholder anchors because comments participate in the DOM tree without triggering layout or paint reflows.

๐Ÿ“Œ Key Takeaways

  • HTML comments begin with <!-- and end with -->.
  • Comments produce no visual paint output on the screen, but they are fully parsed into in-memory CommentNode objects (nodeType === 8).
  • Consecutive dashes (--) inside comment text violate the WHATWG specification and trigger parse errors.
  • Programming language comment syntaxes (// and /* */) are treated as plain text when placed directly in HTML markup.
  • Production build pipelines should strip non-essential comments to reduce payload size and eliminate accidental data leakage.
  • --
โญ LEARN: HTML ๐ŸŒŸ โš”๏ธ QUIZ BATTLE ARENA // ACTIVE
3x
STREAK!
BONUS ACTIVE
COMBO
? Question 1 / 3

What is the numeric nodeType value of an HTML comment node in the DOM?

Question 1 / 3 Topic: HTML Fundamentals
00:45 REMAINING
XP REWARD
+250 XP
3x
STREAK!
BONUS ACTIVE
COMBO
? Question 2 / 3

Which of the following HTML comments violates WHATWG parsing rules and generates a parser error?

Question 2 / 3 Topic: HTML Fundamentals
00:45 REMAINING
XP REWARD
+250 XP
3x
STREAK!
BONUS ACTIVE
COMBO
? Question 3 / 3

What happens if a developer writes // Check user login status inside the <body> of an HTML document?

Question 3 / 3 Topic: HTML Fundamentals
00:45 REMAINING
XP REWARD
+250 XP