EthicsComputerCourses
Join training +91 90532 10052

DOM vs HTML Source Code

HTML · Lesson 123 of 234 Advanced 11 min read Updated

By the end of this lesson you will be able to say which version of a page each browser tool shows, list what the parser and scripts change, explain why the value attribute and property disagree, and choose which version an SEO check or test should read.

What you should know first: DOM Structure & HTML Parsing briefly compared View Source with the Elements panel, and Deep Understanding of HTML Parsing and DOM Tree & Node Relationships explained how the tree is built.

One page, four views

Think of a recipe card and a plate of biryani. The card is the source, the text the server sent. The plate is the DOM, what the cook made after fixing the recipe's mistakes and adding a last-minute garnish. A photo of the plate is a serialisation: the DOM turned back into HTML text at one moment.

ViewHow to open itWhat it really shows
View SourceCtrl+U, or a view-source: URLThe response text, decoded. The browser may request the page again, so a dynamic page can differ from what loaded
Network panel, Response tabF12, Network, click the documentExactly the bytes this page load received
Elements panelF12, ElementsThe live DOM, plus extras that are not HTML: #shadow-root, ::before and ::marker pseudo-elements, badges such as flex
outerHTML and getHTML()Console or codeThe DOM serialised to HTML text at that moment

The Elements panel is not a text file; editing it changes the DOM. For the current DOM as text, right-click a node and choose Copy, then Copy outerHTML, or use code. outerHTML on the root leaves out the doctype:

JavaScript
const html = "<!DOCTYPE html>\n" + document.documentElement.outerHTML;
// outerHTML skips shadow roots. getHTML() can include the serializable ones:
const withShadow = host.getHTML({ serializableShadowRoots: true });

What the parser changes

Serialisation follows fixed rules in the HTML standard. Together with the parser's repairs, the text you get back often differs from what you wrote:

In the sourceIn the serialised DOMWhy
No <head>, <body> or <tbody>All three presentThe tree builder creates them
<p>Text<div><p>Text</p><div>A paragraph cannot contain a <div>
<b>Order <i>now</b> online</i><b>Order <i>now</i></b><i> online</i>Misnested formatting is repaired
<P CLASS=price class=old><p class="price">Names lowercased, first duplicate attribute wins
href=menu.csshref="menu.css"Attribute values always get double quotes
checked/>checked=""Empty value written out; void elements get no slash
&#8377;₹References are decoded; only &, <, >, " and non-breaking spaces are escaped again
A <div> inside <head>The <div> and everything after it in <body>Body content closes the head early

The last row causes real bugs. A stray <div> or text in the head, often from a widget snippet, ends the head early. Every later <meta> and <link> lands in the body, where crawlers may ignore a canonical link or robots tag.

What scripts change

After parsing, scripts keep editing the DOM. A typical page:

  • adds content from an API (prices, reviews, a whole client-rendered app);
  • adds classes such as class="js" on <html>, or dark for a theme;
  • inserts banners, chat buttons and consent dialogs;
  • changes <title> and meta tags in a single-page app.

Browser extensions such as password managers inject nodes too, so your Elements panel may show things visitors never get. Test in a guest window.

In apps that render on the server and then hydrate (attach JavaScript to existing HTML), parser repairs such as a <div> inside a <p> are a classic cause of hydration mismatches; see HTML Hydration & Client-Side Rendering.

Live coding: diff the source against the DOM

Build a tool that parses a messy source, serialises it and prints a line diff: - for source lines, + for DOM lines.

Step 1: put the "server response" in a textarea. Inside a textarea, & must be written as &amp;, so the code shows &amp;#8377; to put the text &#8377; in the box.

Step 2: parse with DOMParser and serialise with the doctype plus outerHTML.

Step 3: diff the texts line by line with a longest common subsequence, the classic diff method, and count elements the source never wrote.

Step 4: tick the box to apply what a page script would do, and compare again.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Source vs DOM diff</title>
  <style>
    body { font-family: sans-serif; padding: 1rem; }
    textarea { width: 100%; height: 11rem; font-family: monospace; }
    pre { background: #f4f4f4; padding: 8px; overflow-x: auto; }
    .del { color: #b91c1c; }
    .add { color: #15803d; }
  </style>
</head>
<body>
  <label for="src">Source as the server sends it:</label>
  <textarea id="src"><!DOCTYPE html>
<HTML>
<title>Kabir's Bakery, Pune</title>
<div class=banner>Fresh today</div>
<link rel=stylesheet href=menu.css>
<P CLASS=price class=old>Pav: &amp;#8377;40 &amp;amp; bun&amp;nbsp;₹30
<table>
<tr><td>Rusk</td><td>₹120</td></tr>
</table>
<p><b>Order <i>now</b> online</i>
<input type=checkbox checked/></textarea>
  <p>
    <label><input type="checkbox" id="script"> Also apply what the page's script would do</label>
    <button id="go">Compare</button>
  </p>
  <pre id="out"></pre>

  <script>
    // What a typical page script might do after loading.
    function pageScript(doc) {
      doc.documentElement.classList.add("js");
      const offer = doc.createElement("p");
      offer.id = "offer";
      offer.textContent = "Diwali offer: 10% off";
      doc.body.prepend(offer);
    }

    // Longest common subsequence of lines, then walk it to print a diff.
    function diff(a, b) {
      const n = a.length, m = b.length;
      const t = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0));
      for (let i = n - 1; i >= 0; i--)
        for (let j = m - 1; j >= 0; j--)
          t[i][j] = a[i] === b[j] ? t[i + 1][j + 1] + 1 : Math.max(t[i + 1][j], t[i][j + 1]);
      const rows = [];
      let i = 0, j = 0;
      while (i < n || j < m) {
        if (i < n && j < m && a[i] === b[j]) { rows.push(["  ", a[i]]); i++; j++; }
        else if (i < n && (j === m || t[i + 1][j] >= t[i][j + 1])) { rows.push(["- ", a[i]]); i++; }
        else { rows.push(["+ ", b[j]]); j++; }
      }
      return rows;
    }

    // Count start tags written in the source and elements present in the DOM.
    function extraElements(source, doc) {
      const written = {};
      for (const [, name] of source.matchAll(/<([a-z][a-z0-9-]*)/gi)) {
        const tag = name.toLowerCase();
        written[tag] = (written[tag] || 0) + 1;
      }
      const present = {};
      for (const el of doc.querySelectorAll("*")) present[el.localName] = (present[el.localName] || 0) + 1;
      return Object.keys(present)
        .filter((tag) => present[tag] > (written[tag] || 0))
        .map((tag) => tag + " +" + (present[tag] - (written[tag] || 0)));
    }

    function compare() {
      const source = document.querySelector("#src").value;
      const doc = new DOMParser().parseFromString(source, "text/html");
      if (document.querySelector("#script").checked) pageScript(doc);
      const serialised = (doc.doctype ? "<!DOCTYPE " + doc.doctype.name + ">\n" : "") +
        doc.documentElement.outerHTML;

      const out = document.querySelector("#out");
      out.textContent = "";
      for (const [mark, line] of diff(source.split("\n"), serialised.split("\n"))) {
        const span = document.createElement("span");
        span.className = mark === "- " ? "del" : mark === "+ " ? "add" : "";
        span.textContent = mark + line + "\n";
        out.append(span);
      }
      out.append("\nElements in the DOM that the source never wrote: " + extraElements(source, doc).join(", "));
    }
    document.querySelector("#go").addEventListener("click", compare);
    compare();
  </script>
</body>
</html>

The first run shows every source line in red and the repaired lines in green, then this summary:

Output
Elements in the DOM that the source never wrote: head +1, body +1, tbody +1, i +1

Read the green lines carefully. <title> moved into a new <head>, the <link> ended up in the body because the <div> closed the head, class=old vanished, the entities became ₹ and &amp;, and a second <i> appeared. With the script box ticked, class="js" and the offer paragraph appear only in the DOM, and the summary adds p +1.

Attribute versus property

An attribute is part of the markup, such as value="Aarav". A property is a field on the JavaScript object, such as input.value. Many properties reflect an attribute: reading or writing one reads or writes the other. id, className and hidden work this way. HTML Attribute Reflection covers the rules in full.

Form controls are the big exception. For an <input>:

  • the value attribute is the default value; the defaultValue property reflects it;
  • the value property is the current value, which starts as the default and changes when the user types;
  • checked works the same way, with defaultChecked reflecting the attribute.

Once the user types (or a script sets input.value), the control is marked dirty, and changing the attribute no longer changes what is shown. Serialisation writes attributes, not properties, so outerHTML keeps showing the old default. URL properties differ too: a.getAttribute("href") returns what you wrote, while a.href returns the full resolved URL.

Try it. Type a new name, untick the box, and press the first button. Then press the second.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Attribute vs property</title>
  <style>
    body { font-family: sans-serif; padding: 1rem; }
    pre { background: #f4f4f4; padding: 8px; overflow-x: auto; }
  </style>
</head>
<body>
  <h1>Railway reservation form</h1>
  <p><label for="name">Passenger name</label> <input id="name" value="Aarav"></p>
  <p><label><input type="checkbox" id="veg" checked> Vegetarian meal</label></p>
  <p><a id="rules" href="rules.html">Booking rules</a></p>
  <button id="show">Show attribute and property</button>
  <button id="set">setAttribute("value", "Priya")</button>
  <pre id="out">Type a new name and untick the box, then press the first button.</pre>

  <script>
    const name = document.querySelector("#name");
    const veg = document.querySelector("#veg");
    const rules = document.querySelector("#rules");

    function show() {
      document.querySelector("#out").textContent = [
        "name.getAttribute('value') " + JSON.stringify(name.getAttribute("value")),
        "name.defaultValue          " + JSON.stringify(name.defaultValue),
        "name.value                 " + JSON.stringify(name.value),
        "veg.hasAttribute('checked') " + veg.hasAttribute("checked"),
        "veg.checked                 " + veg.checked,
        "rules.getAttribute('href') " + JSON.stringify(rules.getAttribute("href")),
        "rules.href                 " + JSON.stringify(rules.href),
        "",
        "name.outerHTML: " + name.outerHTML,
        "veg.outerHTML:  " + veg.outerHTML
      ].join("\n");
    }

    document.querySelector("#show").addEventListener("click", show);
    document.querySelector("#set").addEventListener("click", () => {
      name.setAttribute("value", "Priya");
      show();
    });
  </script>
</body>
</html>
Output
name.getAttribute('value') "Aarav"
name.defaultValue          "Aarav"
name.value                 "Meera"
veg.hasAttribute('checked') true
veg.checked                 false
rules.getAttribute('href') "rules.html"
rules.href                 "https://.../rules.html"

name.outerHTML: <input id="name" value="Aarav">
veg.outerHTML:  <input type="checkbox" id="veg" checked="">

That is after typing "Meera" and unticking the box; rules.href shows the full address. The second button changes the attribute and defaultValue to "Priya", but name.value stays "Meera" because the field is dirty. Pressed before typing, it changes the visible text too.

Why crawlers and tests must read the right version

Google Search. Google's documentation describes three phases: crawl, render and index. Googlebot fetches the source, queues pages for rendering in an evergreen (always up to date) Chromium, and indexes the rendered HTML. Content added by JavaScript can be indexed, but only after rendering, and only if it actually appears. Google does not queue a page for rendering when the source already carries a noindex robots meta tag or header, so removing noindex with JavaScript does not work. The URL Inspection tool in Search Console shows the rendered HTML Google sees.

Link previews. Many link-preview bots for chat and social apps read only the source. Open Graph tags inserted by JavaScript often never reach them, so put og:title and og:image in the server's HTML. See Open Graph & Social Media Metadata.

Validators and audits. The W3C Nu validator checks the source text you give it. Lighthouse and axe run in the browser and audit the rendered DOM. A page can pass one and fail the other.

Automated tests. Browser test tools read the live DOM. In Playwright, for example, page.content() returns the serialised DOM, while the response returned by page.goto() has text() for the original source. toHaveValue() checks the value property, and toHaveAttribute("value", ...) checks the attribute.

JavaScript
// Playwright test (plain code, not runnable here)
const response = await page.goto("/booking");
const source = await response.text();          // the server's HTML
await page.getByLabel("Passenger name").fill("Meera");
const dom = await page.content();              // the DOM serialised now
await expect(page.getByLabel("Passenger name")).toHaveValue("Meera");
await expect(page.getByLabel("Passenger name")).toHaveAttribute("value", "Aarav");

Both assertions pass: the property holds what was typed, and the attribute still holds the default.

Common mistakes

  • Debugging with View Source. It shows the source, not the current tree.
  • Copying from the Elements panel and calling it the source. It is a repaired, script-modified view.
  • Snippets with <div> or text in the <head>. They push later meta and link tags into the body.
  • Checking getAttribute("value") for what the user typed. Read the value property.
  • Adding og: tags or removing noindex only with JavaScript. Preview bots and Google's render queue miss it.

Interview questions

1. What is the difference between View Source and the Elements panel?

View Source shows the HTML text from the server, decoded but not parsed. The Elements panel shows the live DOM after parser repairs and script changes, plus extras such as shadow roots and pseudo-elements. For the exact response of this load, use the Network panel.

2. Why does outerHTML not show what the user typed in an input?

Serialisation writes attributes, and the value attribute is only the default. Typing changes the value property and marks the control dirty. Read input.value for the current value.

3. Name three ways the DOM can differ from the source without any JavaScript.

The parser adds missing html, head, body and tbody elements, repairs bad nesting such as a <div> inside a <p>, and drops duplicate attributes. Body content also closes the head early, moving later head tags into the body.

4. How does Google index JavaScript-heavy pages?

Googlebot crawls the source, renders the page in an evergreen Chromium, and indexes the rendered HTML. A noindex in the source stops the page from being queued for rendering, so JavaScript cannot remove it later.

5. In a browser test, when would you assert the attribute and when the property?

Assert the property, for example with Playwright's toHaveValue(), to check what the user sees or typed. Assert the attribute, with toHaveAttribute(), to check the markup the server or template produced.

Key points

  • Source is the text the server sent; the DOM is the live tree; serialisation turns the DOM back into text.
  • The parser adds elements, fixes nesting, lowercases names, drops duplicate attributes and normalises quotes and entities.
  • Body content inside <head> closes it early and moves later head tags into the body.
  • Scripts and extensions add more changes, so test in a clean profile.
  • Form properties such as value and checked hold the current state; their attributes hold the default.
  • Put SEO and preview metadata in the source; test behaviour on the DOM.

Exercise

Farhan's travel blog in Kochi loads a chat widget whose snippet, pasted into the head, starts with <div id="chat-root"></div>. Below it in the head are <link rel="canonical" href="https://example.com/kochi-food"> and <meta property="og:image" content="/img/appam.jpg">. A script also adds <meta name="description"> after load. Explain where each tag ends up in the DOM and who can see it (Google, a chat preview bot, the user). Then write a corrected head and say where the widget markup should go.

Show solution

The <div> closes the head, so the canonical link and the og:image meta tag land in the body. Google may ignore a canonical link in the body, and preview bots that expect these tags in the head may miss them. The description added by script exists only in the rendered DOM: Google may see it after rendering, but source-only preview bots never will.

HTML
<head>
  <meta charset="utf-8">
  <title>Kochi food trail: appam, stew and more</title>
  <meta name="description" content="Farhan's guide to breakfast in Fort Kochi.">
  <link rel="canonical" href="https://example.com/kochi-food">
  <meta property="og:image" content="https://example.com/img/appam.jpg">
  <script src="/js/chat.js" defer></script>
</head>
<body>
  <!-- page content -->
  <div id="chat-root"></div>
</body>

The widget's <div> moves to the end of the body, its script is deferred, and every meta tag sits in the source head with an absolute image URL.

Quick Quiz

1. Which tool shows exactly the bytes this page load received for the HTML document?

2. A user types "Isha" into <input value="Kabir">. What does input.getAttribute("value") return?

3. Why can a <link rel="canonical"> written in the head end up in the body?

4. Which check reads the source rather than the rendered DOM?

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