DOM API

Interesting resources

What is the DOM

The DOM (Document Object Model) is the underlying data structure of a html page


                

Working with the dom

Attributes, properties and children

Attributes and children map to different properties on the DOM element

An attribute does not always map to a property of the same name and properties can have a different datatype than string

Querying the DOM

Navigating the DOM

The following samples are all relative to the element with the class "reference"

get the current parent element

get siblings

get children

Creating, Adding and Removing Elements

Creating a new Element

Append a new element

prepend a new element

create and append text content

add text to an element

add html to an element Use with care! you have to sanitize user input before using innerHTML

remove a node

TreeWalker

Events

The general DOM paradigm is settings data via properties and exposing changed data or user interaction with events

Event handling is split into three phases, capture phase, target phase and bubbling phase.

Events can be triggered by user interaction, for example mouse events (move, click), keyboard events, focus events, typing in textfields or custom events

Important: not all events bubble, also for custom events it is possible to prevent bubbling. Events which are not composed will also not bubble through a shadow dom boundary

Adding event listeners

Removing event listeners

Preventing propagation or default behaviour

Event target

Manually Dispatching Events

Working effectively with the DOM

As you see the DOM API only provides primitives and low level functions to work with. Thats the main reason templating frameworks like (p)react, lit-html, etc.. exist. The w3c is currently working on a Template Instantiation Proposal to mitigate these issues

ToDo Example

Add event listener to form to handle form submission in javascript

Prevent the browser from executing the default action and send the form to an URL

Check for form validity and call addToDo function with new text

Function to handle adding of todos

get the #todo element from the DOM

create a new list item element...

...set the content...

...add an event listener to the delete button to handle deletion of todos...

...and add the new todo to the list

This line introduces a potential XSS security risk for injecting scripts...

...to mitigate this we set only text content and no html

It is always a good idea to separate the view from the underlying data model...

...so instead of adding a new todo to the dom, we add a todo to the data model and sync the dom...

...same for the deletion of todos...

...the sync function will iterate through the todos and create html elements accordingly...

...before each sync the previous content will be deleted

Always re-creating all elements can have a bad performance impact...

...so we only create new elements if new todos are added...

...and update the other todos only if the text changed...

...entries which are not longer needed will be removed...

...because we need a reference to a event listener to remove it we have to refactor our remove event listeners...

...and dispatch a remove event with the index which should be removed, the index is stored in a custom attribute on the button

...this sync algorithm is 'unkeyed' because the entry in the list has no direct relation to a DOM node, the dom nodes are reused with new data

There are plenty of templating frameworks out there which will automate dom manipulation for you...

...so your code gets more readable and easier to use

Templating Frameworks

Popular frameworks like Angular, Vue and Svelte also have their own template system. A more comprehensive list along with benchmarks for the different frameworks can be found on Stefan Krauses github

The global window object

Until builtin modules are a thing in the browser the only way to access the browser APIs is with the global window object

All builtin objects like Array, Set, Map, Promise are defined on the global window object and are automatically injected and available in the script scope

calling window.Promise.resolve() is the same as Promise.resolve() because these objects are automatically injected

You can't share global Objects of different execution environments, for example iframes

You can share the data however message passed with window.postMessage/window.onmessage between windows or workers are cloned with the Structure Cloning Algorithm

Because of Meltdown/Spectre SharedArrayBuffer to share a byte range was disabled, but it can be used again with the appropriate CORS headers

window.document

the window.document property provides all APIs to work and manipulate with the DOM of the currently loaded document

window.navigator property

The window.navigator property provides functions to interact with the browser and the APIs the browser provides

A small overview of the provided APIs and functions

  • window.navigator.language return the current set language
  • window.navigator.geoLocation access geolocation API
  • window.navigator.usb access WebUSB API
  • window.navigator.bluetooth access WebBluetooth API

window.location

The window.location object provides you with all information about your current browsing location

do not confuse location with navigator.geoLocation

window.history

the window.history object can be used to manipulate the browsers back/forward history and shown URL

If you develop single page applications this API is important for routing and "back" behavior

window.localstorage

the window.localstorage object provides an alternative for cookies to save information to a specific origin

Every "origin" has its own local storage can can't read data from other origins

window.crypto

Never roll your own crypto and use the functions provided by window.crypto for hashing/encrypt/decrypt