Interacting with the DOM

The DOM is a convention used for interacting with HTML elements - a platform independent model, meaning it is up to the vendor to implement it.

HTML nodes are in a tree format, so using JavaScript it is possible to create, update, delete HTML elements. It is a combination of an API and a tree data structure.

We can also add or trigger events, change css styles et al - all using the DOM API provided by the browser.

Finding an element


Single elements that are returned by the DOM implement the HTMLElement, Element, Node, EventTarget, ParentNode, ChildNode interfaces.

Nodelists and Live nodelists

A Nodelist is just that, a list (an Array-like object, but not an Array) of DOM nodes.

The difference between "live" and "not live" is "live" is a reference to the node, so changes are reflected in the list - live updates of DOM elements.

These selectors produce live node lists:


Static list:



Every html element has a LOT of properties including the following:

  • innerHTML
  • innerText
  • dataset
  • textContent
  • id
  • className
  • classList
  • tagName

They also have these methods:

  • setAttribute
  • getAttribute
  • hasAttribute
  • removeAttribute
  • addEventListener
  • removeEventListener

You'll be using these ones a lot.


As the DOM is a tree structure, to traverse the tree you can use methods on any element:

  • parentNode
  • children
  • childNodes
  • firstElementChild
  • lastElementChild
  • nextElementSibling
  • previousElementSibling

CRUD methods

As well as traversing, we can create nodes. You have to have a starting point, so that will be a node that you have selected.

  • removeChild
  • appendChild
  • insertBefore
  • insertAdjacentHTML

Events and EventTarget

We can add interactivity using the DOM methods addEventListener, removeEventListener, dispatchEvent. The event object has a type, target, currentTarget. The callback takes an event object - which is the event on the DOM element, hence is the element that had the event triggered.

There are also methods on this event object such as preventDefault, stopPropagating, stopImmediatePropagation.

Event phases


  • CAPTURING_PHASE: trickles down from window to target's parent, executing handlers added with useCapture = true
  • AT_TARGET or 'Target phase': on the target itself, executes handlers with useCapture = false
  • BUBBLING_PHASE or 'Bubbling phase': Bubbles up from the target's parent to window, executing handlers with useCapture = false