What is the DOM, and what kinds of node does it contain?
The Document Object Model is the browser's in-memory representation of a web page. When the browser parses the HTML, it builds a tree of objects, and that tree is the DOM. JavaScript does not see the markup itself, it sees this tree, and every change you make is a change to the tree.
The tree contains several kinds of node, and they are told apart by a numeric type. Element nodes are the tags themselves and carry the node type one. Text nodes are the character content between tags and carry the type three. Attribute nodes hold the values of an element's attributes. Comment nodes carry the type eight. And the document node is the root of the whole tree, with the element node for the html tag directly below it.
// A tiny stand-in for the browser DOM, so this example runs in Node.
const element = (tag, attrs = {}) => ({
nodeType: 1,
tagName: tag.toUpperCase(),
attributes: attrs,
childNodes: [],
parentNode: null,
appendChild(child) {
child.parentNode = this;
this.childNodes.push(child);
return child;
},
});
const textNode = (value) => ({ nodeType: 3, nodeValue: value, parentNode: null });
const list = element("ul", { id: "topics" });
const item = element("li");
item.appendChild(textNode("Closures"));
list.appendChild(item);
console.log(list.tagName); // "UL"
console.log(list.attributes.id); // "topics"
console.log(list.childNodes.length); // 1
console.log(list.childNodes[0].tagName); // "LI"
console.log(list.childNodes[0].childNodes[0].nodeValue); // "Closures"
console.log(list.childNodes[0].parentNode === list); // trueTwo distinctions matter in practice. The childNodes collection includes every kind of child, so text nodes are in there as well as elements, while the children collection contains only elements. A parent always has a reference back to its parentNode, which is what makes walking upwards possible.
The DOM is not the same as the HTML source. The browser corrects malformed markup, adds implied elements such as the body tag, and the tree you get is not always the tree you wrote. The DOM is also live: change it and the browser repaints the page, so it is a model of what is on screen rather than a document.