- The Window object
- The Document object
- Types of Nodes
- Traversing the DOM
- Editing the DOM
The DOM is the browser’s internal representation of a web page. When the browser retrieves your HTML from your server, the parser analyzes the structure of your code and creates a model of it. Based on this model, the browser then renders the page on the screen.
In Single Page Applications, the DOM continuously changes to reflect what appears on the screen, and as a developer you can inspect it using the Browser Developer Tools.
The DOM is standardized by WHATWG in the DOM Living Standard Spec.
- inspect the page structure
- access the page metadata and headers
- edit the CSS styling
- attach or remove event listeners
- edit any node in the page
- change any node attribute
.. and much more.
The main 2 objects provided by the DOM API that you you will interact the most with are
The Window object
window object represents the window that contains the DOM document.
window.document points to the
document object loaded in the window.
Properties and methods of this object can be called without referencing
window explicitly, because it represents the global object. So, the previous property
window.document is usually called just
Here is a list of useful properties you will likely reference a lot:
consolepoints to the browser debugging console. Useful to print error messages or logging, using
console.errorand other tools (see the Browser DevTools article)
documentas already said, points to the
documentobject, key to the DOM interactions you will perform
historygives access to the History API
locationgives access to the Location interface, from which you can determine the URL, the protocol, the hash and other useful information.
localStorageis a reference to the Web Storage API localStorage object
sessionStorageis a reference to the Web Storage API sessionStorage object
window object also exposes useful methods:
alert(): which you can use to display alert dialogs
postMessage(): used by the Channel Messaging API
requestAnimationFrame(): used to perform animations in a way that’s both performant and easy on the CPU
setInterval(): call a function every n milliseconds, until the interval is cleared with
clearInterval(): clears an interval created with
setTimeout(): execute a function after ‘n’ milliseconds
setImmediate(): execute a function as soon as the browser is ready
addEventListener(): add an event listener to the document
removeEventListener(): remove an event listener from the document
See the full reference of all the properties and methods of the
window object at https://developer.mozilla.org/en-US/docs/Web/API/Window
The Document object
document object represents the DOM tree loaded in a window.
Here is a representation of a portion of the DOM pointing to the head and body tags:
Here is a representation of a portion of the DOM showing the head tag, containing a title tag with its value:
Here is a representation of a portion of the DOM showing the body tag, containing a link, with a value and the href attribute with its value:
The Document object can be accessed from
window.document, and since
window is the global object, you can use the shortcut
This Document object has a ton of properties and methods. The Selectors API methods are the ones you’ll likely use the most:
You can get the document title using
document.title, and the URL using
document.URL. The referrer is available in
document.referrer, the domain in
document object you can get the body and head Element nodes:
document.documentElement: the Document node
You can also get a list of all the element nodes of a particular type, like an HTMLCollection of all the links using
document.links, all the images using
document.images, all the forms using
The document cookies are accessible in
document.cookie. The last modified date in
You can do much more, even get old school and fill your scripts with
See the full reference of all the properties and methods of the
document object at https://developer.mozilla.org/en-US/docs/Web/API/Document
Types of Nodes
There are different types of nodes, some of which you have already seen in the example images above. The main ones you will encounter are:
- Document: the document Node, the start of the tree
- Element: an HTML tag
- Attr: an attribute of a tag
- Text: the text content of an Element or Attr Node
- Comment: an HTML comment
- DocumentType: the Doctype declaration
Traversing the DOM
The DOM is a tree of elements, with the Document node at the root, which points to the
html Element node, which in turn points to its child element nodes
body, and so on.
From each of those elements, you can navigate the DOM structure and move to different nodes.
Getting the parent
Every element has just one parent.
They are almost the same, except when ran on the
parentNode returns the parent of the specified node in the DOM tree, while
parentElement returns the DOM node’s parent Element, or null if the node either has no parent, or its parent isn’t a DOM Element.
People usually use
Getting the children
To check if a Node has child nodes, use
Node.hasChildNodes() which returns a boolean value.
To access all the Children Element Nodes of a node, use
The DOM also exposes a
Node.children method. However, it does not just include Element nodes, but also the white space between elements as Text nodes. This is not something you generally want.
To get the first child Element Node, use
Node.firstElementChild. To get the last child Element Node, use
The DOM also exposes
Node.lastChild, with the difference that they do not “filter” the tree for Element nodes only. They will also show empty Text nodes that indicate white space.
In short, to navigate children Element Nodes use
Getting the siblings
In addition to getting the parent and the children, since the DOM is a tree you can also get the siblings of any Element Node.
You can do so using
The DOM also exposes
nextSibling, but as their counterparts described above, they include white spaces as Text nodes, so you generally avoid them.
Editing the DOM
The DOM offers various methods to edit the nodes of the page and alter the document tree.
document.createElement(): creates a new Element Node
document.createTextNode(): creates a new Text Node
you can create new elements, and add them to the DOM elements you want as children, by using
const div = document.createElement('div') div.appendChild(document.createTextNode('Hello world!'))
first.removeChild(second)removes the child node “second” from the node “first”.
document.insertBefore(newNode, existingNode)inserts “newNode” as a sibling of “existingNode”, placing it before that in the DOM tree structure.
element.appendChild(newChild)alters the tree under “element”, adding a new child Node “newChild” to it, after all the other children.
element.prepend(newChild)alters the tree under “element”, adding a new child Node “newChild” to it, before other child elements. You can pass one or more child Nodes, or even a string which will be interpreted as a Text node.
element.replaceChild(newChild, existingChild)alters the tree under “element”, replacing “existingChild” with a new Node “newChild”.
element.insertAdjacentElement(position, newElement)inserts “newElement” in the DOM, positioned relatively to “element” depending on “position” parameter value. See the possible values.
element.textContent = 'something'changes the content of a Text node to “something”.
More browser tutorials:
- Some useful tricks available in HTML5
- How I made a CMS-based website work offline
- The Complete Guide to Progressive Web Apps
- The Fetch API
- The Push API Guide
- The Channel Messaging API
- Service Workers Tutorial
- The Cache API Guide
- The Notification API Guide
- Dive into IndexedDB
- The Selectors API: querySelector and querySelectorAll
- The Document Object Model (DOM)
- The Web Storage API: local storage and session storage
- Learn how HTTP Cookies work
- The History API
- The WebP Image Format
- XMLHttpRequest (XHR)
- An in-depth SVG tutorial
- What are Data URLs
- Roadmap to learn the Web Platform
- CORS, Cross-Origin Resource Sharing
- Web Workers
- The requestAnimationFrame() guide
- What is the Doctype
- Working with the DevTools Console and the Console API
- The Speech Synthesis API
- How to add a class to a DOM element
- How to loop over DOM elements from querySelectorAll
- How to remove a class from a DOM element
- How to check if a DOM element has a class
- How to change a DOM node value
- How to add a click event to a list of DOM elements returned from querySelectorAll
- WebRTC, the Real Time Web API
- How to replace a DOM element
- How to only accept images in an input file field
- Why use a preview version of a browser?
- The Blob Object
- The File Object
- The FileReader Object
- The FileList Object
- The URL Object
- Typed Arrays
- The DataView Object
- The BroadcastChannel API
- The Streams API
- The FormData Object
- The Navigator Object
- How to use the Geolocation API
- How to use getUserMedia()
- How to use the Drag and Drop API
- How to work with scrolling on Web Pages
- Keyboard events
- Mouse events
- Touch events
- How to remove all children from a DOM element
- How to make a page editable in the browser
- How to remove all CSS from a page at once
- How to use insertAdjacentHTML
- Safari, warn before quitting
- How to reset a form
- How to use Google Fonts