When building a website, you’ll often encounter the term DOM - which stands for the Document Object Model. The DOM is a programming interface that represents a webpage as a structured tree of nodes, with each node correlating to an HTML element (like a heading tag, paragraph, and link). This allows programmatic access to navigate and modify content on a page dynamically.
What is the DOM?
When your browser loads the HTML code, it parses through it and builds a tree of objects made from elements on the page. The <html> element at the top would be the root of the tree, and under that you’d find the <head> and <body> nodes, and within that their child objects. The DOM is often described as a standardized API for HTML content. If a program needs to update the content of your page, it would interface with the DOM.
It’s also important to mention that the DOM itself is language-neutral. It’s not a part of JavaScript, but JavaScript does just so happen to be the best way to interact with it.
DOM Behind the Scenes
When a browser loads a website, the HTML is parsed into a DOM tree and the CSS into the CSSOM (CSS Object Model), which represents all of the style rules of your objects. Once complete, the browser combines the DOM and CSSOM to figure out what nodes should look like and where they should appear, calculating the exact position and size of each DOM element.
The DOM is a live, dynamic structure, so JavaScript and other code can change nodes after a page loads, with the site updating instantly without needing a reload.
Interacting with the DOM
The browser exposes the DOM via the `document` object, which JavaScript can then use to interact with it. Using the DOM API, you can perform a variety of actions to make a static page more dynamic and interactive. Some things include:
- Selecting elements by doing `document.getElementById`, which returns the button or element for that ID
- Reading or modifying content on a page by changing the `element.textContent` or `element.innerHTML`.
- Dynamically applying or altering the CSS for an element by changing the property styles (for example, doing `element.style.backgroundColor = “yellow”` to set something yellow)
- Adding or removing elements on a page by doing `document.createElement` or `element.removeChild`
Why the DOM matters
Without the DOM, websites as we know it wouldn’t exist! The DOM empowers everything from a simple web script to complex applications by enabling dynamic content, and it truly is the bridge between simple HTML and JavaScript. By understanding what the DOM is and how it works, developers can use it in their own sites to build engaging features for their users.