The DOM API, 80/20

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.

Code

show(x) prints x below. It's a helper for this page, like console.log.


  

The page it works on

Written as HTML, then changed only by the code you run. Reset the page (or picking a step) rebuilds it from that HTML.

Tree before Run


  

Tree now


  

Red lines are gone, green lines are new. Whitespace text nodes are left out.

The short list

To…Use
find elementsdocument.getElementById(id), document.querySelector(css), document.querySelectorAll(css), el.closest(css)
move around the treeel.parentElement, el.children, el.firstElementChild, el.nextElementSibling, el.previousElementSibling
createdocument.createElement(tag), el.cloneNode(true)
attach, move, removeparent.append(…), parent.prepend(…), el.before(…), el.after(…), el.replaceWith(…), el.remove(), parent.replaceChildren(…)
change what's insideel.textContent, el.innerHTML (only for HTML you wrote)
change attributes, classes, styleel.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 userel.addEventListener("click", fn), event.target