What is the DOM, and what kinds of node does it contain?
The Document Object Model is the browser's in-memory picture of a web page. When the browser reads your HTML, it builds a tree of objects, and that tree is the DOM. JavaScript does not see your markup directly. It sees this tree, and every change you make is a change to the tree.
The tree holds several kinds of node, and you tell them apart by a number called the node type. Element nodes are the tags themselves, and their node type is one. Text nodes are the characters between the tags, and their node type is three. Attribute nodes hold the values of an element's attributes. Comment nodes have the type eight. The document node is the root of the whole tree, and the element node for the html tag sits directly below it.
// A tiny stand-in for the browser DOM, so this example runs in Node.
function element(tag, attrs) {
if (!attrs) {
attrs = {};
}
return {
nodeType: 1,
tagName: tag.toUpperCase(),
attributes: attrs,
childNodes: [],
parentNode: null,
appendChild: function (child) {
child.parentNode = this;
this.childNodes.push(child);
return child;
},
};
}
function textNode(value) {
return { 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('tag name ->', list.tagName);
console.log('attributes.id ->', list.attributes.id);
console.log('child count ->', list.childNodes.length);
console.log('first child ->', list.childNodes[0].tagName);
console.log('text inside it ->', list.childNodes[0].childNodes[0].nodeValue);
console.log('parent link ->', list.childNodes[0].parentNode === list);
Two differences matter in real work. 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. Every node also keeps a reference back to its parentNode, and that is what makes it possible to walk up the tree.
The DOM is not the same thing as your HTML source. The browser corrects broken markup, adds elements that you did not write such as the body tag, and the tree you get is not always the tree you typed. The DOM is also live. Change it and the browser repaints the page, so it is a model of what is on the screen right now and not a document that sits still.