How DOM and CSSOM created during Browser Page Rendering

The Document Object Model (DOM) and the CSS Object Model (CSSOM) are critical components of web browsers that represent the structure and styling of a web page, respectively. Here, I’ll explain how the DOM and CSSOM are created and provide examples.

Creating the DOM (Document Object Model):

The DOM is a hierarchical tree-like structure that represents the structure of an HTML document. It’s created as follows:

  1. Parsing HTML: When the browser receives an HTML document from the server, it starts parsing the HTML code.
  2. Constructing the DOM Tree: During parsing, the browser creates a DOM tree by breaking down the HTML elements, attributes, and text content into nodes.

Here’s a simple example:

<!DOCTYPE html>
<html>
  <head>
    <title>DOM Example</title>
  </head>
  <body>
    <h1>Hello, World!</h1>
    <p>This is a paragraph.</p>
  </body>
</html>

The resulting DOM tree might look like this:

- Document
  - html
    - head
      - title
        - TextNode: "DOM Example"
    - body
      - h1
        - TextNode: "Hello, World!"
      - p
        - TextNode: "This is a paragraph."

In this example, the DOM tree represents the structure of the HTML document, with nodes for elements, attributes, and text content.

Creating the CSSOM (CSS Object Model):

The CSSOM represents the styles applied to the elements in the DOM. It’s created as follows:

  1. Parsing CSS: While parsing the HTML, the browser encounters CSS stylesheets (external or inline) linked or embedded in the document.
  2. Constructing the CSSOM Tree: The browser processes the CSS to construct a CSSOM tree, which contains rules, selectors, and style declarations.

Here’s an example:

/* styles.css */
body {
    font-family: Arial, sans-serif;
    background-color: #f0f0f0;
}
h1 {
    color: #0074d9;
}

Assuming this CSS is linked to the HTML document:

<!DOCTYPE html>
<html>
  <head>
      <title>CSSOM Example</title>
      <link rel="stylesheet" type="text/css" href="styles.css">
  </head>
  <body>
      <h1>Hello, CSSOM!</h1>
  </body>
</html>

The resulting CSSOM tree might look like this:

- CSSOM
  - Rules
    - Rule: body
      - Property: font-family: Arial, sans-serif
      - Property: background-color: #f0f0f0
    - Rule: h1
      - Property: color: #0074d9

In this example, the CSSOM tree represents the CSS rules applied to the elements in the DOM.

Combining DOM and CSSOM:

After creating both the DOM and CSSOM, the browser combines them to create a Render Tree. The Render Tree contains only the nodes that need to be rendered on the web page and includes information about visual styles, dimensions, and positions. The Render Tree is used to render the final visual representation of the web page on the screen.

For more detailed understanding of how DOM and CSS DOM are combined please refere to Next article —  Here

You might also like