JavaScript DOM Manipulation
Master DOM manipulation. Learn how to select elements, change content, styles, and handle user interactions.
JavaScript DOM Manipulation
What's the DOM?
When you write HTML, the browser turns it into something called the DOM (Document Object Model). Think of it like this:
``` Your HTML File: ┌─────────────────────┐ │ <h1>Hello</h1> │ │ <p>World</p> │ └─────────────────────┘ │ │ Browser reads it │ ┌────────▼────────────┐ │ DOM (in memory) │ │ ┌───────────────┐ │ │ │ h1: "Hello" │ │ ← JavaScript can change this │ │ p: "World" │ │ ← JavaScript can change this │ └───────────────┘ │ └─────────────────────┘ ```
The DOM is like a live version of your HTML that JavaScript can read and change. When JavaScript changes the DOM, the webpage updates instantly.
Finding Elements on the Page
Before you can change something, you need to find it. Like finding a book in a library - you need to know where it is.
**Find by ID (most common):** ```javascript const heading = document.getElementById('myHeading'); ```
This finds the element with `id="myHeading"` in your HTML.
**Find by class:** ```javascript const boxes = document.getElementsByClassName('box'); ```
This finds all elements with `class="box"`.
**Modern way (recommended):** ```javascript const heading = document.querySelector('#myHeading'); const boxes = document.querySelectorAll('.box'); ```
`querySelector` finds one element. `querySelectorAll` finds all matching elements.
Changing Text Content
Once you have an element, you can change what it says:
```javascript const heading = document.getElementById('title'); heading.textContent = 'New Title'; ```
**What happens:** 1. Find the element with id "title" 2. Change its text to "New Title" 3. The page updates immediately
Changing HTML Content
You can also change the HTML inside an element:
```javascript const div = document.getElementById('content'); div.innerHTML = '<p>This is <strong>bold</strong> text</p>'; ```
This replaces everything inside the element with new HTML.
Changing Styles
You can change how elements look:
```javascript const box = document.getElementById('myBox'); box.style.color = 'red'; box.style.backgroundColor = 'blue'; box.style.fontSize = '20px'; ```
**Important:** CSS properties with hyphens (like `background-color`) become camelCase in JavaScript (`backgroundColor`).
Adding New Elements
You can create new elements and add them to the page:
```javascript // Step 1: Create a new element const newParagraph = document.createElement('p'); newParagraph.textContent = 'This is a new paragraph';
// Step 2: Find where to add it const container = document.getElementById('container');
// Step 3: Add it to the page container.appendChild(newParagraph); ```
**What happens:** 1. Create a new `<p>` element 2. Give it some text 3. Find the container where you want it 4. Add it to that container
Removing Elements
You can also remove elements:
```javascript const element = document.getElementById('toRemove'); element.remove(); ```
This removes the element from the page completely.
Real Example: Dynamic List
Let's say you're building a to-do list where users can add items:
```javascript function addTodoItem(text) { // Create new list item const newItem = document.createElement('li'); newItem.textContent = text; // Find the list const todoList = document.getElementById('todoList'); // Add the new item todoList.appendChild(newItem); }
// Use it addTodoItem('Buy groceries'); addTodoItem('Walk the dog'); ```
Each time you call this function, a new item appears on the page.
How It All Works Together
``` 1. HTML loads ┌─────────────┐ │ <h1 id="x"> │ └─────────────┘ 2. JavaScript finds it document.getElementById('x') 3. JavaScript changes it element.textContent = 'New' 4. Page updates User sees the change! ```
Quick Tips
1. **Always find elements first** - You can't change what you haven't found 2. **Use querySelector for modern code** - It's more flexible 3. **Use textContent for plain text** - Safer than innerHTML 4. **Use innerHTML only when you need HTML** - Be careful with user input
The DOM is how JavaScript talks to your webpage. Without it, JavaScript couldn't change anything on the page. With it, you can make websites that respond and update in real-time.