DOM Manipulation
Learn to select and modify HTML elements with JavaScript.
What is the DOM?
The Document Object Model (DOM) is a programming interface for HTML. It represents the page as a tree of objects that JavaScript can interact with.
Key Concept: The DOM allows JavaScript to access and change all the elements of an HTML document dynamically.
Selecting Elements
There are several ways to select elements from the DOM:
JavaScript
// Select by ID - returns single element
const header = document.getElementById('header');
// Select by class - returns HTMLCollection
const buttons = document.getElementsByClassName('btn');
// Select by tag - returns HTMLCollection
const paragraphs = document.getElementsByTagName('p');
// Select with CSS selector - returns first match
const first = document.querySelector('.card');
// Select all with CSS selector - returns NodeList
const all = document.querySelectorAll('.card');
Try it yourself
Output
Modifying Element Content
Try it yourself
Output
Security Warning: Never use
innerHTML with user-provided content. Use textContent instead to prevent XSS attacks.
Modifying Attributes
Try it yourself
Output
Modifying Styles
Try it yourself
Output
Best Practice: Instead of setting many inline styles, define CSS classes and toggle them with
classList. This keeps styling in CSS where it belongs.
Creating and Removing Elements
Try it yourself
Output
Traversing the DOM
Try it yourself
Output
Live Demo Area
This area demonstrates DOM manipulation in action:
This text can be changed!
Interact with the demo above
Output
Challenge: Build a List
Create a function that takes an array of items and adds them as list items to an unordered list. Use DOM methods to create and append elements.
Your solution
Output