The DOM has hundreds of functions and properties, but about twenty of them do most everyday work: find an element, create one, attach, move or remove it, change its text, attributes, classes and style, and react to clicks. Pick a step, read the code, press Run, and see what it did to the page and to the tree. Edit the code and run your own too. Notes. New to the DOM? Start with DOM.
show(x) prints x below.
It's a helper for this page, like console.log.
Written as HTML, then changed only by the code you run. Reset the page (or picking a step) rebuilds it from that HTML.
Red lines are gone, green lines are new. Whitespace text nodes are left out.
| To… | Use |
|---|---|
| find elements | document.getElementById(id), document.querySelector(css), document.querySelectorAll(css), el.closest(css) |
| move around the tree | el.parentElement, el.children, el.firstElementChild, el.nextElementSibling, el.previousElementSibling |
| create | document.createElement(tag), el.cloneNode(true) |
| attach, move, remove | parent.append(…), parent.prepend(…), el.before(…), el.after(…), el.replaceWith(…), el.remove(), parent.replaceChildren(…) |
| change what's inside | el.textContent, el.innerHTML (only for HTML you wrote) |
| change attributes, classes, style | el.id, el.hidden and other properties, el.setAttribute(name, value), el.getAttribute(name), el.classList.add / remove / toggle, el.style.color, el.dataset.name |
| react to the user | el.addEventListener("click", fn), event.target |