HTML DOM

DOM (Document Object Model)

The HTML DOM (Document Object Model) is a programming interface that represents an HTML page as a tree of objects. When a browser loads a page, it builds the DOM so that JavaScript can read and change the page's content, structure, and styles.


What is the DOM?

The DOM is a language-neutral, in-memory representation of the document. Every part of the page - the document itself, each element, each attribute, and each piece of text - becomes a node object. JavaScript treats the whole page as the global document object, which is the entry point into the DOM tree.

With the DOM, JavaScript can create new HTML elements, change all the HTML elements and attributes on the page, change all the CSS styles, remove existing elements, and react to all the events on the page.

The DOM Tree

The DOM organizes the page as a hierarchical tree. The topmost node is the document node. Below it sits the root <html> element, which contains <head> and <body>, which in turn contain the rest of the page. Nested tags become child nodes, and tags at the same level are sibling nodes.

The HTML that produces the tree below
<!DOCTYPE html>
<html>
  <head>
    <title>My Page</title>
  </head>
  <body>
    <h1>Hello</h1>
    <p>Welcome!</p>
  </body>
</html>

The document node has one child (<html>). <html> has two children (<head> and <body>). <head> contains <title>, and <body> contains an <h1> and a <p>. The text "Hello" and "Welcome!" are themselves text nodes, children of their respective elements.

Types of Nodes

  • Document node - the whole page, exposed to JavaScript as document.
  • Element nodes - HTML tags such as <div>, <p>, and <a>.
  • Attribute nodes - attributes on elements, such as id or href.
  • Text nodes - the actual text inside elements.
  • Comment nodes - HTML comments <!-- ... -->.

How JavaScript Accesses and Updates the DOM

JavaScript reaches into the tree using finder methods on document, then reads or writes properties on the nodes it finds. The example below selects an element by its id and changes its text and color.

Access an element and update it
// Find the element with id "demo"
const el = document.getElementById("demo");

// Read its current content
console.log(el.innerHTML);

// Update its content and style
el.innerHTML = "Text changed by the DOM!";
el.style.color = "green";

getElementById returns the matching element node. innerHTML reads or replaces the HTML inside it, and the style object lets you set inline CSS. The moment you assign a new value, the browser re-renders that part of the page.

💡

Common finder methods include getElementById, getElementsByTagName, getElementsByClassName, querySelector (first match for a CSS selector), and querySelectorAll (all matches).

Ready to use your HTML skills?

Find web development internships and fresher jobs across India.

Browse Web Dev Internships