DOM Manipulation
45 minThe Document Object Model (DOM) is the bridge between JavaScript and HTML. It represents the page structure as a tree of objects, allowing scripts to dynamically read, modify, add, or delete content and styles.
Accessing elements is the first step. Modern methods like `querySelector()` and `querySelectorAll()` allow you to find elements using CSS selectors, replacing older, specific methods like `getElementById()` or `getElementsByClassName()`.
Once you have an element, you can modify it using properties like `textContent` (safe text), `innerHTML` (HTML parsing, risky if user input), `style` (CSS), or `classList` (adding/removing classes).
Creating and inserting new elements involves `document.createElement()`, `appendChild()`, or the newer `append()` and `prepend()` methods. This allows for dynamic UI generation based on data.
Key Concepts
- The DOM Tree structure.
- Selecting elements (`querySelector`).
- Modifying content (`textContent` vs `innerHTML`).
- Manipulating classes (`classList`).
- Traversing the DOM (parent, children, siblings).
Learning Objectives
Master
- Selecting single and multiple elements
- Safely updating text and HTML content
- Dynamically creating and removing elements
- Toggling CSS classes for state changes
Develop
- Understanding reflow and repaint costs
- Security awareness (XSS prevention)
- Building dynamic user interfaces
Tips
- Cache your DOM selectors in variables if you use them more than once.
- Use `textContent` instead of `innerHTML` whenever possible to prevent XSS attacks.
- Use `classList.toggle('active')` instead of manually checking and adding/removing classes.
- Use `documentFragment` when appending many elements to avoid multiple reflows.
Common Pitfalls
- Overusing `innerHTML`, which re-parses all children and kills event listeners.
- Touching the DOM in a loop (huge performance hit); build a string or fragment first.
- Assuming `querySelectorAll` returns an Array (it returns a NodeList, use `Array.from()` to map/reduce).
- Forgetting that scripts in `<head>` run before the DOM is ready (use `defer` or `DOMContentLoaded`).
Summary
- The DOM makes HTML dynamic.
- Selection, Modification, and Creation are core skills.
- Performance matters when touching the DOM.
- Security is critical when handling HTML strings.
Exercise
Write JavaScript to change the text of an HTML element. (Imagine an element with id='demo').
// HTML: <p id="demo">Old Text</p>
document.getElementById("demo").innerHTML = "Hello World!";
Exercise Tips
- Use textContent instead of innerHTML for plain text to prevent XSS attacks.
- Cache the element reference if you'll use it multiple times.
- Check if the element exists before trying to modify it.
- Try using querySelector as a modern alternative to getElementById.