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

element.querySelector(cssElement);
document.getElementById(idOfElement);

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:

element.getElementsByClassName(cssClassName);
element.getElementsByTagName(tagName);
document.getElementById('elementId').childNodes;

Static list:

element.querySelectorAll(cssSelector);

HTMLElement

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.

Traversal

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 event.target is the element that had the event triggered.

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

Event phases

There are 4 phases, NONE, CAPTURING_PHASE, AT_TARGET, BUBBLING_PHASE.

  • 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

References