Document Object Model (DOM)
DOM stands for Document Object Model.
When we send HTML to a browser, the browser renders the HTML (displays it in a window) and it also creates a giant object that represents the web page. As web developers, we can interact with this object (DOM) and make changes to the it without modifying the actual source code. The browser will redraw the web page to reflect any change we make to the DOM.
DOM Tree
Given this HTML:
The HTML's structure (nested tags, etc.) can be visualised as a tree in the DOM:
The
head
andbody
are children of thedocument
The
body
is the parent element of theh1
and thediv
with a class ofcontainer
The
h1
element and thecontainer
element are siblingsThe
li
elements are also siblings of each otherWhat relationship does the image have with the
h3
? What about the image and thediv
with the class ofcontainer
?
Being able to relate and navigate the different elements in this way is often referred to as 'traversal' and there are JavaScript methods that will help you access the element you want. Oftentimes you'll want to target the child elements or the parent element, rather than the element itself. This will become more apparent as you start to build more complex things.
Nodes vs Elements
A node is the generic name for any type of object in the DOM hierarchy. A node could be one of the built-in DOM elements such as document
or document.body
, it could be an HTML tag specified in the HTML such as <input>
or <p>
or it could be a text node that is created to hold a block of text inside an element. So, in a nutshell, nodes are any DOM object while elements are the HTML elements.
The DOM tree diagram above is a simplified tree that only shows the element nodes. A more complete DOM tree will look like the following:
This tree shows the text nodes including comments and the whitespace in the HTML file (line breaks and indentation).
DOM Tree visualisers:
Last updated
Was this helpful?