DOM Structure & HTML Parsing
By the end of this lesson you will be able to explain how a browser turns the text of an HTML file into a tree of objects, name the kinds of nodes in that tree, and predict a few of the fixes the browser makes to your markup.
You have already seen the basic tree in HTML Document Structure and one repair in HTML Elements, Tags & Attributes. This lesson is a friendly introduction. Level 4 returns to the same ideas in depth, starting with Deep Understanding of HTML Parsing.
From text to a tree
An HTML file is just text. The browser first converts it into a structure it can work with. This is called parsing. Think of a teacher reading a handwritten answer sheet: first she makes out the individual words, then she understands how the sentences fit together.
The browser works in three broad stages:
- Bytes to characters. The file arrives as bytes. The browser decodes them using the character encoding, which is why
<meta charset="utf-8">matters for Hindi text and the ₹ sign. - Characters to tokens. The tokenizer reads the characters one by one and groups them into tokens: a doctype, a start tag, an end tag, a piece of text, a comment.
- Tokens to a tree. The tree builder takes each token and adds the right object to a growing tree, the DOM (Document Object Model).
Here is a tiny piece of HTML and the tokens the tokenizer would produce for it.
<p class="note">Fees due <b>Friday</b></p>Start tag: p (attribute class="note")
Text: "Fees due "
Start tag: b
Text: "Friday"
End tag: b
End tag: pThe tree builder turns those tokens into a small tree: a p element with two children, a text node and a b element, which has its own text node.
Kinds of nodes
Every object in the DOM tree is a node. Most of what you write becomes one of a few node types. JavaScript can tell them apart with the nodeType property, which is a number.
| Node type | Created from | nodeType |
|---|---|---|
| Document | The whole page (the root of the tree) | 9 |
| DocumentType | <!DOCTYPE html> | 10 |
| Element | Tags such as <p> and <li> | 1 |
| Text | The text between tags | 3 |
| Comment | <!-- ... --> | 8 |
Attributes such as class are not children in the tree. They belong to their element, a bit like the name label stuck on a tiffin box rather than a separate box inside it.
Whitespace becomes text nodes
When you indent your HTML, the spaces and line breaks between tags are also text. The parser keeps most of them as whitespace text nodes. They usually do not change what you see, but they do appear in the tree. Run this example to list every child node of a short menu.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Node Explorer</title>
</head>
<body>
<h1>Breakfast at Indore Junction</h1>
<ul id="menu">
<li>Poha</li>
<!-- seasonal item -->
<li>Jalebi</li>
</ul>
<pre id="out"></pre>
<script>
const menu = document.querySelector("#menu");
const lines = [
"children: " + menu.children.length,
"childNodes: " + menu.childNodes.length,
""
];
for (const node of menu.childNodes) {
lines.push(node.nodeType + " " + node.nodeName + " " + JSON.stringify(node.nodeValue));
}
document.querySelector("#out").textContent = lines.join("\n");
</script>
</body>
</html>children: 2 childNodes: 7 3 #text "\n " 1 LI null 3 #text "\n " 8 #comment " seasonal item " 3 #text "\n " 1 LI null 3 #text "\n "
The list has two elements but seven nodes: two li elements, one comment and four whitespace text nodes (\n is a line break). So in scripts, children (elements only) is usually what you want, and childNodes (every node) can surprise you.
The parser fixes your HTML
The HTML parser never stops with an error. When the tokens break a rule, it follows exact steps written in the HTML standard to build a sensible tree. Every modern browser follows the same steps, so the repaired tree is the same in Chrome, Firefox and Safari.
Three repairs are worth knowing now.
- Paragraphs close themselves. A
<p>cannot contain block elements such as another<p>, a<div>, a heading or a list. When one of those starts, the parser closes the open paragraph first. - Tables get a
<tbody>. If you put<tr>straight inside<table>, the parser adds a<tbody>element around the rows. - Missing structure is created. If you leave out
<html>,<head>or<body>, the parser creates them.
Run this example. It shows what the parser built from two short pieces of markup, and what a script builds.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Parser Repairs</title>
</head>
<body>
<div id="notices"><p>Exam on Monday<p>Holiday on Friday<div>Fees are due</div></div>
<table id="fees"><tr><td>Class 9</td><td>₹2,400</td></tr></table>
<pre id="out"></pre>
<script>
const built = document.createElement("table");
built.append(document.createElement("tr"));
document.querySelector("#out").textContent =
"Notices:\n" + document.querySelector("#notices").innerHTML +
"\n\nParsed table:\n" + document.querySelector("#fees").innerHTML +
"\n\nScript-built table:\n" + built.outerHTML;
</script>
</body>
</html>Notices: <p>Exam on Monday</p><p>Holiday on Friday</p><div>Fees are due</div> Parsed table: <tbody><tr><td>Class 9</td><td>₹2,400</td></tr></tbody> Script-built table: <table><tr></tr></table>
The second <p> closed the first, and the <div> closed the second, so the "Fees are due" line is not inside any paragraph. The parsed table gained a <tbody>, but the table built with createElement did not. The repairs belong to the parser, not to the DOM itself. This explains a classic bug: CSS such as table > tr matches nothing in a parsed table, because the rows are inside <tbody>.
View Source vs the Elements panel
Your browser offers two views of a page.
| View | How to open it | What it shows |
|---|---|---|
| View Source | Ctrl+U, or right-click and choose View page source | The exact text the server sent, before parsing |
| Elements panel | F12, or right-click and choose Inspect | The live DOM: after parser repairs and after scripts ran |
Try it with the repairs example above, saved as a file and opened in your browser:
- Step 1: press Ctrl+U. You see your markup exactly as you typed it, with no
<tbody>and no closing</p>tags. - Step 2: press F12 and open the Elements panel. You see
<tbody>inside the table, and each paragraph closed. - Step 3: scroll to the
<pre>. In the Elements panel it contains the text the script wrote. In View Source it is empty, because scripts run after the source arrives.
When a page behaves strangely, trust the Elements panel. It shows the tree your CSS and JavaScript actually work on. A deeper comparison is in DOM vs HTML Source Code.
Common mistakes
- Thinking the DOM equals your file. The parser adds, closes and moves elements.
- Using
childNodes[0]to get the first element. It is often a whitespace text node; usechildren[0]orfirstElementChild. - Putting a
<div>or list inside a<p>. The paragraph closes early and your CSS no longer matches. - Writing
table > trselectors. Parsed rows live inside<tbody>. - Debugging with View Source. It shows the original text, not the current tree.
Interview questions
1. What is the DOM?
The Document Object Model is the tree of objects the browser builds from HTML. Each element, piece of text and comment becomes a node. JavaScript and CSS work on this tree, not on the original text.
2. What are the main steps of HTML parsing?
The browser decodes bytes into characters using the character encoding. The tokenizer turns characters into tokens such as start tags, end tags, text and comments. The tree builder then turns those tokens into DOM nodes, fixing errors as it goes.
3. What is the difference between children and childNodes?
children contains only element nodes. childNodes contains every node, including text nodes created by whitespace and comment nodes. That is why childNodes often has more entries than expected.
4. Why does a table in DevTools show <tbody> when the source has none?
The HTML parser inserts a <tbody> when it finds <tr> directly inside <table>. DOM methods such as appendChild do not do this, so tables built by script may have no <tbody>.
5. How is View Source different from the Elements panel?
View Source shows the raw HTML the server sent. The Elements panel shows the current DOM, including parser repairs and every change made by scripts.
Key points
- Parsing turns bytes into characters, characters into tokens, and tokens into the DOM tree.
- The main node types are document, doctype, element, text and comment.
- Indentation creates whitespace text nodes, so
childNodesis longer thanchildren. - The parser repairs markup in the same way in every browser: it closes paragraphs, adds
<tbody>and creates missing structure. - Those repairs happen only during parsing, not when scripts build elements.
- View Source shows what was sent; the Elements panel shows what was built.
Exercise
Kabir's results page in Rohtak has this markup: <p>Results for Class 10<ol><li>Aarav: 92%</li><li>Meera: 95%</li></ol></p> followed by <table><tr><th>Subject</th><th>Marks</th></tr></table>. Predict the DOM. Then write a full page that wraps this markup in a <div> and prints the div's innerHTML, to check your prediction. Finally, write corrected markup that needs no repair.
Show solution
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Class 10 Results</title>
</head>
<body>
<div id="results"><p>Results for Class 10<ol><li>Aarav: 92%</li><li>Meera: 95%</li></ol></p>
<table><tr><th>Subject</th><th>Marks</th></tr></table></div>
<pre id="out"></pre>
<script>
document.querySelector("#out").textContent = document.querySelector("#results").innerHTML;
</script>
</body>
</html>The parser closes the <p> when <ol> starts, turns the stray </p> into a new empty paragraph after the list, and adds a <tbody> inside the table. Corrected markup:
<p>Results for Class 10</p>
<ol>
<li>Aarav: 92%</li>
<li>Meera: 95%</li>
</ol>
<table>
<tbody>
<tr><th>Subject</th><th>Marks</th></tr>
</tbody>
</table>Quick Quiz
1. Which part of the parser groups characters into start tags, end tags and text?
The tokenizer produces tokens; the tree builder turns them into DOM nodes.
2. A <ul> with two <li> elements, written on separate indented lines, has how many children?
children counts only elements; the whitespace text nodes appear only in childNodes.
3. What does the parser do when a <div> starts inside an open <p>?
A paragraph cannot contain block elements, so the parser ends it before the div.
4. Where can you see the <tbody> the parser added?
The Elements panel shows the live DOM, including parser repairs.
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
