Forms and debugging

Source code and the DOM

Compare the HTML you wrote with the repaired DOM the browser created, and use the difference to find invalid nesting.

8 minute lesson

~~~

View Page Source shows the HTML the browser received.

The Elements panel shows the DOM the browser built after parsing that HTML. They can be different.

SOURCEPDIVINVALID NESTINGBROWSER PARSERDOMBODYPDIVREPAIRED SIBLINGS
The source is what you wrote. The DOM is what the browser built.

For example, a paragraph cannot contain a div:

<p>
  Introduction
  <div>Important note</div>
</p>

The browser closes the paragraph before the div. It may also create another empty paragraph for the closing p tag.

The page can still look reasonable. The DOM no longer has the structure you intended.

Use valid siblings instead:

<p>Introduction</p>
<div>Important note</div>

Compare both views

When an element appears in a surprising place:

  1. inspect it in the Elements panel
  2. look at its parent and nearby siblings
  3. open View Page Source
  4. compare the same section
  5. validate the source

Do not copy the repaired DOM back into your file without understanding it. Fix the invalid source that made the repair necessary.

JavaScript can also change the DOM after the page loads. If the source is valid but the DOM changes later, a script may be responsible.

The distinction is simple:

Source is the input. The DOM is the browser’s result.

Lesson completed