The Document Object Model

The Document Object Model, a.k.a. the DOM, is the connection between HTML and Javascript.

The document as a tree

When the browser loads a web page, it turns the text of an HTML tree into an internal representation in order to render it.

This HTML

<p>Here is some <i>italic</i> text.</p>a

Becomes something like this

Note: In computer science, unlike in biology, trees typically grow from the top.

Tree terminology

Each ellipse in the tree is called a “node”.

The node at the top of the tree is called the “root”.

A node with nodes below it is called a “parent node” and the nodes below “child nodes”.

Nodes with no children are called “leaves”.

The DOM exposes that tree to Javascript

Each node in the tree is represented by an object.

And the objects are linked together so you can get from the object represented a <p> tag to it’s children, which represent the text and the <i> element.

DOM objects have lots of functionality

  • You can access objects representing elements in the original HTML

  • You can remove elements via those objects

  • You can add new elements

Getting existing elements

  • document.querySelector(selector) - finds the first element that matches the given selector. Selectors are in the same syntax as we used in CSS.

  • document.querySelectorAll(selector) - get a list of all the elements that match the given selector.

Creating elements

  • document.createElement(tag) - make a new element with the given tag.

  • document.createTextNode(text) - make a new chunk of text.

Attributes

  • element.setAttribute(name, value) - set the value of the named attribute on element.

  • element.getAttribute(name) - get the value of the named attribute on element.

  • element.removeAttribute(name) - remove the named attribute from element.

Manipulating the DOM

To create:

<p>Here is some <i>italic</i> text.</p>a

We can write this:

const body = document.querySelector('body');
const p = document.createElement('p');
const i = document.createElement('i');

p.append(document.createTextNode('This is some '));
i.append(document.createTextNode('italic'));
p.append(i);
p.append(document.createTextNode(' text.'));

body.append(p);