Course contentsShow
← Web Development
Lesson 671 of 2,98212. The Document Object ModelFree lesson

DOM vs HTML Source

Why the DOM can differ from HTML source due to JavaScript modifications and browser corrections.

DOM vs HTML Source

You'll learn why what you see in "View Source" can be completely different from what JavaScript and developer tools show you.

The Fundamental Difference

When you write HTML and save it in a .html file, that's your HTML source — the original code you authored. But when a browser loads that file, it builds the DOM (Document Object Model) in memory. These two can diverge significantly, and understanding why is crucial for debugging.

Why They Differ

Browser Corrections

Browsers automatically fix malformed HTML when building the DOM. If you forget to close a <p> tag or nest elements incorrectly, the browser silently corrects these mistakes in the DOM — but your original HTML source remains unchanged on disk.

<!-- HTML Source (broken) -->
<p>Hello <strong>world

<!-- DOM (auto-corrected) -->
<p>Hello <strong>world</strong></p>

JavaScript Modifications

Once the page loads, JavaScript can completely transform the DOM. You might add elements, remove them, change text, or modify attributes. These changes exist only in the DOM — they never touch your original HTML file.

If you "View Source" in your browser, you see the original HTML that was sent over the network. But if you "Inspect Element" in DevTools, you see the current, live DOM with all JavaScript modifications and browser corrections applied.

The Analogy

Think of HTML source as a blueprint, and the DOM as the actual building. Once construction (page load) begins, the builder (browser) might fix errors in the blueprint and later renovations (JavaScript) might add rooms or change layouts. The original blueprint stays the same, but the building evolves.

Key Takeaway: The DOM is the browser's live, in-memory representation of your page — it can differ from your HTML source due to browser corrections and JavaScript modifications. Always inspect the DOM in DevTools when debugging, not just the source code.