The Document Object Model, a.k.a. the DOM, is the connection between HTML and Javascript.
When the browser loads a web page, it turns the text of an HTML tree into an internal representation in order to render it.
<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.
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”.
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.
You can access objects representing elements in the original HTML
You can remove elements via those objects
You can add new 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.
document.createElement(tag)
- make a new element with the given tag.
document.createTextNode(text)
- make a new chunk of text.
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.
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);