How Browsers Read HTML
Prerequisites: Your first web page
When a browser loads a page, it:
- Downloads the HTML file.
- Parses it — reads the tags from top to bottom and builds a tree of objects called the DOM (Document Object Model).
- Fetches the resources the HTML refers to: stylesheets, images, scripts, fonts.
- Renders the page by combining the DOM with CSS, working out the layout, and painting pixels.
The DOM is a tree
This markup:
<body>
<h1>Title</h1>
<p>Some <em>important</em> text.</p>
</body>
becomes this tree:
body
├── h1
│ └── "Title"
└── p
├── "Some "
├── em
│ └── "important"
└── " text."
Elements contain other elements and text. An element inside another is its child; the outer one is its parent. CSS and JavaScript both work on this tree.
Browsers repair mistakes
HTML parsing never "fails". The standard defines exactly how to recover from every error, so all browsers repair broken markup the same way. That doesn't mean mistakes are harmless — the repair may not be what you meant.
Below, the <b> and <i> tags overlap (b closes while i is still
open), and a <div> appears after a <p> that was never closed. A
small script (you'll learn scripts later) prints part of the DOM the
browser actually built:
<!-- Broken on purpose: overlapping tags -->
<p>First paragraph
<div>A box</div>
<p>Second <b>bold <i>both</b> italic?</i></p>
<script>
const paragraphs = document.querySelectorAll("p");
console.log(paragraphs.length + " paragraphs");
console.log(paragraphs[0].parentElement.tagName);
console.log(paragraphs[1].innerHTML);
</script>
2 paragraphs
BODY
Second <b>bold <i>both</i></b><i> italic?</i>
- The first paragraph ended automatically when the
<div>began — a paragraph can't contain adiv. This one is actually allowed: the</p>end tag is optional in the standard. Thedivis a sibling of the paragraph, not inside it. - The overlapping tags were repaired: the browser closed the
i, then opened a newielement for the rest of the text. The DOM now has twoielements, although you wrote one.
Catching mistakes with a validator
The same markup in the Nu Html Checker:
<!-- Wrong: overlapping tags -->
<p>First paragraph
<div>A box</div>
<p>Second <b>bold <i>both</b> italic?</i></p>
error: End tag 'b' violates nesting rules.
The checker accepts the omitted </p> (it's legal) but reports the
overlap. In the online checker each message comes with a line number.
Fix errors from the top down — one early mistake often causes several
later messages.
Key points
- The browser builds a DOM tree from your HTML.
- Mistakes never stop a page from loading, but they can change its structure in surprising ways.
- Use View Source to see what you sent, the Elements panel to see what the browser built, and a validator to find the difference.