Skip to main content

What happens when the browser parses HTML?

HTML parsing is the process by which the browser reads HTML code and turns it into a data structure that a machine understands: a DOM tree (Document Object Model).

In simpler terms, the browser translates HTML text into a visual structure that it, and JavaScript, can then work with.


Step by step: what the browser does when parsing HTML

1. Loading the file

The browser receives the HTML document (from a server or locally) and starts reading it line by line, top to bottom. It does not wait for the whole file to load: parsing and loading happen in parallel.


2. Lexical analysis (tokenization)

HTML is just text, and the browser needs to figure out where the tags are and where the content is. It splits the text into tokens: small meaningful units.

For example, the code:

html
<p>Hello, world!</p>

breaks down into tokens:

javascript
Opening tag: <p> Text: "Hello, world!" Closing tag: </p>

3. Syntax analysis

After tokenization, the browser checks the structure of the document: nesting, whether tags are closed correctly, compliance with standards. If it finds an error (for example, a missing </div>), it tries to guess what the developer meant. HTML is a "forgiving" language, so the page almost always renders even if the code is not perfect.


4. Building the DOM tree

From the resulting tokens, the browser creates the DOM (Document Object Model): an internal tree of elements. Each tag becomes a node, and nested elements form a hierarchy.

Example:

html
<body> <h1>Heading</h1> <p>Text</p> </body>

Turns into a tree:

javascript
body ├── h1 │ └── "Heading" └── p └── "Text"

5. Detecting external resources

When the browser encounters tags like:

html
<link rel="stylesheet" href="style.css"> <script src="script.js"></script> <img src="photo.jpg">

it sends additional requests to the server to load the CSS, scripts and images. Some of them (especially <script>) can pause parsing until they finish executing.


6. Passing the DOM to the rendering stage

Once the DOM is ready (or partially ready), the browser passes it on: to the rendering stage, where CSS is applied, element positions are calculated, and the page is drawn.


Summary:

StageWhat the browser does
1. LoadingFetches the HTML file
2. TokenizationSplits text into tags and content
3. Syntax analysisChecks structure and nesting
4. Building the DOMCreates the tree of elements
5. Loading resourcesLoads CSS, JS, images
6. RenderingPasses the result to the screen

In simple terms: When parsing HTML, the browser reads the code, breaks it down by meaning, builds a model of the page (the DOM) and prepares everything needed to draw the page on screen.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.