DOM Manipulation
Select, create, update and remove elements with the Document Object Model, and understand what frameworks automate for you.
Beginner · about 6 hours · difficulty 2/5
Learn first: Modern JavaScript and Error Handling
The DOM is the live object tree the browser builds from your HTML. JavaScript reads and changes it to make pages interactive. Frameworks like React exist to manage DOM updates for you, and you will use them far better if you have done it by hand first.
Core operations
- Select:
document.querySelector(".card")andquerySelectorAll(returns a static NodeList you canforEach). - Create and insert:
document.createElement,append,prepend,before,after,replaceWith,remove. - Read and change content:
textContent(safe) vsinnerHTML(parses HTML, dangerous with user input because of XSS). - Attributes and classes:
setAttribute,datasetfordata-*, andclassList.add/remove/toggle. - Styles: prefer toggling classes over setting
element.styledirectly.
Performance habits
- Batch changes: build nodes in a
DocumentFragmentor a<template>and insert once. - Avoid reading layout (
offsetWidth,getBoundingClientRect) in the middle of writes; that forces synchronous layout. - For long lists, render only what is visible (virtualisation) or paginate.
Observers
IntersectionObserver (is this element on screen, great for lazy loading and infinite scroll), ResizeObserver (did this element change size) and MutationObserver (did the DOM change) replace many polling hacks.
Move on when you can build a small interactive UI (say, a filterable list) with vanilla JavaScript and no framework, keeping it free of innerHTML with user data.
Key concepts
- querySelector and querySelectorAll
- Creating and inserting nodes
- textContent vs innerHTML: innerHTML with user input enables XSS
- classList and dataset
- template element and fragments
- Traversal: parent, children, closest
- IntersectionObserver and ResizeObserver
- MutationObserver
Mini project
Build a vanilla JS contact list: render from an array, add and delete contacts, filter by search text, and lazy-load avatars with IntersectionObserver.
Check yourself
Why is setting innerHTML with a user's comment dangerous, and what should you use instead?
Free resources
- Document Object Model (DOM) (MDN)
- Browser: Document, Events, Interfaces (javascript.info)