Lesson 4 โข Beginner
DOM Manipulation ๐จ
Learn how to interact with and modify HTML elements using JavaScript โ bring your webpages to life with dynamic content, styles, and interactivity.
What You'll Learn in This Lesson
- โWhat the DOM is and how it works
- โSelect elements with querySelector
- โChange text content and innerHTML
- โModify styles and CSS classes dynamically
- โCreate, append, and remove elements
- โNavigate the DOM tree with parent/child relationships
๐ก Running Code Locally: While this online editor runs real JavaScript, some advanced examples may have limitations. For the best experience:
- Download Node.js to run JavaScript on your computer
- Use your browser's Developer Console (Press F12) to test code snippets
- Create a
.htmlfile with<script>tags and open it in your browser
๐ณ What is the DOM?
The Document Object Model (DOM) is a programming interface for web documents. It represents your HTML page as a tree of objects that JavaScript can interact with.
Think of the DOM as a live representation of your webpage that you can read and modify in real-time.
๐ง Real-World Analogy:
Imagine your HTML is like a blueprint of a house. The DOM is the actual house that's been built from that blueprint. With JavaScript, you can walk through that house, change the paint colors, move furniture around, or even add new rooms โ all while people are inside!
Everything on a webpage โ every paragraph, image, button, and div โ is represented as an object in the DOM tree.
๐ฏ Why DOM Manipulation Matters
Without the DOM, web pages would be static and boring. DOM manipulation is what makes the web interactive:
- โUpdate content without reloading the page (like social media feeds)
- โRespond to user actions (clicks, typing, scrolling)
- โCreate animations and visual effects
- โBuild dynamic forms with validation
- โShow/hide elements based on conditions
๐ Selecting Elements โ Finding What You Need
Before you can manipulate an element, you need to select it. JavaScript gives you several powerful methods to find elements in the DOM.
๐ Method 1: getElementById
The most direct way to select an element โ by its unique id attribute.
const header = document.getElementById('main-header');
console.log(header); // Returns the element with id="main-header"null if not found).๐ Method 2: getElementsByClassName
Select all elements with a specific class name. Returns an HTMLCollection (array-like object).
const buttons = document.getElementsByClassName('btn');
console.log(buttons[0]); // First button
console.log(buttons.length); // Number of buttons๐ Method 3: querySelector (Modern & Recommended)
The most versatile method โ uses CSS selectors to find elements. Returns the first match.
// Select by class
const container = document.querySelector('.container');
// Select by ID
const header = document.querySelector('#main-header');
// Select by tag
const firstParagraph = document.querySelector('p');
// Advanced: select nested elements
const submitBtn = document.querySelector('form .submit-btn');๐ Method 4: querySelectorAll
Like querySelector, but returns all matching elements as a NodeList.
const allButtons = document.querySelectorAll('.btn');
// Loop through all buttons
allButtons.forEach(button => {
console.log(button.textContent);
});โ Best Practice:
Use querySelector and querySelectorAll for modern projects. They're more flexible and work just like CSS selectors you already know!
โ๏ธ Changing Content โ textContent vs innerHTML
Once you've selected an element, you can change what's inside it.
๐ค Using textContent (Safer)
Changes the plain text inside an element. HTML tags are treated as text, not rendered.
const heading = document.querySelector('h1');
heading.textContent = "Welcome to my website!";
// HTML tags are escaped (safe from XSS attacks)
heading.textContent = "<script>alert('hack')</script>";
// Displays as text, doesn't run code โ
๐๏ธ Using innerHTML (More Powerful)
Changes the HTML content inside an element. Tags are parsed and rendered.
const container = document.querySelector('.container');
container.innerHTML = "<h2>New Title</h2><p>Some text</p>";
// Can add multiple elements at once
container.innerHTML = `
<div class="card">
<h3>Card Title</h3>
<p>Card content</p>
</div>
`;โ ๏ธ Security Warning:
Be careful with innerHTML when inserting user-provided content! It can expose your site to XSS (Cross-Site Scripting) attacks. Use textContent for user input, or sanitize the HTML first.
๐ Example: Updating a Counter
const counter = document.querySelector('#counter');
let count = 0;
setInterval(() => {
count++;
counter.textContent = `Count: ${count}`;
}, 1000); // Updates every second๐จ Changing Styles โ Making Things Beautiful
You can modify CSS styles directly using JavaScript's style property.
๐๏ธ Basic Styling
const box = document.querySelector('.box');
// Change individual properties
box.style.color = "blue";
box.style.backgroundColor = "#f0f0f0";
box.style.fontSize = "20px";
box.style.padding = "15px";
box.style.borderRadius = "8px";background-color) become camelCase in JavaScript (backgroundColor).๐ญ Multiple Styles at Once
const element = document.querySelector('.element');
// Using cssText (overwrites existing styles)
element.style.cssText = `
color: white;
background-color: #333;
padding: 20px;
border-radius: 10px;
`;๐ Example: Theme Switcher
const body = document.body;
const themeBtn = document.querySelector('#theme-toggle');
themeBtn.addEventListener('click', () => {
if (body.style.backgroundColor === 'white' || !body.style.backgroundColor) {
// Dark mode
body.style.backgroundColor = '#1a1a1a';
body.style.color = '#ffffff';
} else {
// Light mode
body.style.backgroundColor = 'white';
body.style.color = '#000000';
}
});โ Best Practice:
For complex styling, it's better to add/remove CSS classes rather than inline styles. This keeps your styling logic in CSS where it belongs!
๐ท๏ธ Working with Classes โ The Professional Way
The classList API is the modern, clean way to manage CSS classes on elements.
โ Adding Classes
const button = document.querySelector('.btn');
// Add a single class
button.classList.add('active');
// Add multiple classes
button.classList.add('primary', 'large', 'animated');โ Removing Classes
// Remove a single class
button.classList.remove('active');
// Remove multiple classes
button.classList.remove('large', 'animated');๐ Toggling Classes
The most useful method โ adds the class if it's not there, removes it if it is.
const menu = document.querySelector('.menu');
const toggleBtn = document.querySelector('#menu-toggle');
toggleBtn.addEventListener('click', () => {
menu.classList.toggle('open'); // Switches between open/closed
});โ Checking if a Class Exists
if (element.classList.contains('active')) {
console.log('Element is active!');
}๐ Real-World Example: Tabs
const tabs = document.querySelectorAll('.tab');
tabs.forEach(tab => {
tab.addEventListener('click', () => {
// Remove 'active' from all tabs
tabs.forEach(t => t.classList.remove('active'));
// Add 'active' to clicked tab
tab.classList.add('active');
});
});- โข No need to manually parse/split strings
- โข Prevents accidentally removing other classes
- โข More readable and maintainable code
๐๏ธ Creating & Adding Elements โ Build on the Fly
JavaScript lets you create brand new HTML elements and insert them into your page dynamically.
๐ Creating Elements
// Step 1: Create the element
const newDiv = document.createElement('div');
// Step 2: Add content
newDiv.textContent = "I'm a new div!";
// Step 3: Add styling/classes
newDiv.classList.add('card');
newDiv.style.padding = '20px';
// Step 4: Add to the page
document.body.appendChild(newDiv);๐ฆ Inserting Elements โ Different Ways
const container = document.querySelector('.container');
const newElement = document.createElement('p');
newElement.textContent = "New paragraph";
// Method 1: Add as last child
container.appendChild(newElement);
// Method 2: Add as first child
container.insertBefore(newElement, container.firstChild);
// Method 3: Modern - insertAdjacentElement
container.insertAdjacentElement('afterbegin', newElement); // Start
container.insertAdjacentElement('beforeend', newElement); // End
container.insertAdjacentElement('beforebegin', newElement); // Before container
container.insertAdjacentElement('afterend', newElement); // After container๐๏ธ Removing Elements
const element = document.querySelector('.remove-me');
// Modern way
element.remove();
// Old way (still works)
element.parentNode.removeChild(element);๐ Example: To-Do List
const todoList = document.querySelector('#todo-list');
const addButton = document.querySelector('#add-todo');
const input = document.querySelector('#todo-input');
addButton.addEventListener('click', () => {
// Create new list item
const li = document.createElement('li');
li.textContent = input.value;
li.classList.add('todo-item');
// Add delete button
const deleteBtn = document.createElement('button');
deleteBtn.textContent = 'ร';
deleteBtn.addEventListener('click', () => li.remove());
li.appendChild(deleteBtn);
todoList.appendChild(li);
// Clear input
input.value = '';
});๐ง Working with Attributes โ The Details
Attributes are the properties you set in HTML tags, like id, src, href, data-*, etc.
๐ฏ Getting Attributes
const link = document.querySelector('a');
const img = document.querySelector('img');
// Get attribute values
console.log(link.getAttribute('href'));
console.log(img.getAttribute('src'));
console.log(img.getAttribute('alt'));โ๏ธ Setting Attributes
const button = document.querySelector('button');
// Set attributes
button.setAttribute('disabled', 'true');
button.setAttribute('aria-label', 'Submit form');
button.setAttribute('data-action', 'submit');๐๏ธ Removing Attributes
button.removeAttribute('disabled');๐ Data Attributes (data-*)
Custom attributes that start with data- are perfect for storing extra information.
// HTML: <div id="user" data-id="123" data-role="admin"></div>
const user = document.querySelector('#user');
// Access via dataset
console.log(user.dataset.id); // "123"
console.log(user.dataset.role); // "admin"
// Set new data attribute
user.dataset.status = "active";
// Creates: data-status="active"๐ซ Common Mistakes to Avoid
โ Mistake 1: Selecting Before DOM is Ready
// โ BAD - Script runs before HTML loads
const button = document.querySelector('.btn'); // null!
button.addEventListener('click', ...); // Error!
// โ
GOOD - Wait for DOM to load
document.addEventListener('DOMContentLoaded', () => {
const button = document.querySelector('.btn');
button.addEventListener('click', ...);
});โ Mistake 2: Not Checking if Element Exists
// โ BAD - Assumes element exists
const header = document.querySelector('.header');
header.textContent = "New title"; // Error if null!
// โ
GOOD - Check first
const header = document.querySelector('.header');
if (header) {
header.textContent = "New title";
}โ Mistake 3: Using innerHTML with User Input
// โ BAD - XSS vulnerability
const userInput = "<script>alert('hacked')</script>";
element.innerHTML = userInput; // Script runs!
// โ
GOOD - Use textContent for user input
element.textContent = userInput; // Safe, displays as textโ Mistake 4: Modifying DOM in a Loop (Slow)
// โ BAD - Multiple reflows
for (let i = 0; i < 1000; i++) {
const div = document.createElement('div');
div.textContent = i;
document.body.appendChild(div); // Triggers reflow each time
}
// โ
GOOD - Build first, append once
const fragment = document.createDocumentFragment();
for (let i = 0; i < 1000; i++) {
const div = document.createElement('div');
div.textContent = i;
fragment.appendChild(div);
}
document.body.appendChild(fragment); // Single reflowโ Best Practices
- โUse querySelector/querySelectorAll โ Most flexible and modern approach
- โPrefer classList over style โ Keep styling in CSS, logic in JavaScript
- โUse textContent for user input โ Prevents XSS attacks
- โCache element selections โ Store references in variables instead of querying repeatedly
- โUse DocumentFragment for bulk operations โ Better performance
- โAlways check if elements exist โ Prevents null reference errors
- โUse semantic HTML โ Makes DOM manipulation easier and more accessible
๐งช Interactive Code Practice
Try out DOM manipulation in this live editor. The code demonstrates selecting, creating, and modifying elements.
DOM Manipulation Practice
Practice DOM manipulation techniques
// ========================================
// DOM MANIPULATION PRACTICE
// ========================================
console.log("๐ณ DOM Manipulation Demo\n");
// 1. Selecting Elements
console.log("=== Selecting Elements ===");
const body = document.body;
console.log("Body element:", body.tagName);
// 2. Creating a New Element
console.log("\n=== Creating Elements ===");
const card = document.createElement("div");
card.textContent = "Hello from JavaScript! ๐";
card.style.padding = "20px";
car
...๐ Quick Reference Guide
๐ Selection Methods
getElementById(id)โ Get element by IDquerySelector(selector)โ First match (CSS selector)querySelectorAll(selector)โ All matchesgetElementsByClassName()โ By class namegetElementsByTagName()โ By tag name
๐๏ธ Creation Methods
createElement(tag)โ Create new elementappendChild(element)โ Add as last childinsertBefore(new, ref)โ Insert before referenceremoveChild(element)โ Remove child elementelement.remove()โ Remove element itself
โ๏ธ Content Methods
textContentโ Get/set text (safe)innerHTMLโ Get/set HTML (powerful)valueโ Get/set form input valueinnerTextโ Get/set visible text
๐จ Style & Class Methods
element.style.propertyโ Set inline styleclassList.add()โ Add CSS classclassList.remove()โ Remove CSS classclassList.toggle()โ Toggle CSS classclassList.contains()โ Check if class exists
๐ง Attribute Methods
getAttribute(name)โ Get attribute valuesetAttribute(name, val)โ Set attributeremoveAttribute(name)โ Remove attributehasAttribute(name)โ Check if existsdataset.propertyโ Access data-* attributes
๐ Traversal Methods
parentElementโ Get parent elementchildrenโ Get child elementsfirstElementChildโ First childlastElementChildโ Last childnextElementSiblingโ Next sibling
๐ฏ Practice Challenges
Test your DOM manipulation skills with these challenges:
Challenge 1: Profile Card Creator
Create a function that generates a user profile card with:
- โข Profile picture (use an img element)
- โข Name and role
- โข Background color based on role (admin = blue, user = green)
- โข Click event that logs the user's details
Challenge 2: Dynamic Form Validator
Create a form validator that:
- โข Selects an input field
- โข Adds a red border if input is empty
- โข Shows an error message below the field
- โข Removes errors when user types
Challenge 3: Color Palette Generator
Build a function that:
- โข Creates 5 colored div boxes
- โข Each box has a random background color
- โข Displays the hex code in the box
- โข Clicking a box copies the color code
Challenge 4: Table Row Striping
Write code that:
- โข Selects all rows in a table
- โข Adds "odd" or "even" class to alternating rows
- โข Adds hover effect using classList
- โข Makes clicking a row highlight it
๐ก Bonus Challenge:
Build a mini shopping cart that lets users add items, increase quantity, remove items, and see the total price update in real-time โ all using DOM manipulation!
๐ฌ Recap
- โThe DOM is a tree representation of your HTML that JavaScript can manipulate
- โUse querySelector/querySelectorAll for modern, flexible element selection
- โtextContent is safe for user input, innerHTML is powerful but risky
- โclassList is the best way to manage CSS classes dynamically
- โYou can create, modify, and delete elements on the fly
- โAlways check if elements exist before manipulating them
- โDOM manipulation is what makes web pages interactive and dynamic
๐ก Final Thought
DOM manipulation is the bridge between your data and what users see. Master it, and you can build anything โ from simple counters to complex web applications!
End of Lesson 4 โ DOM Manipulation
Next up: Learn how to respond to user actions with Event Handling! ๐
๐ Quick Reference โ DOM Manipulation
| Task | Code |
|---|---|
| Select element | document.querySelector('.btn') |
| Change text | el.textContent = "Hello" |
| Add class | el.classList.add('active') |
| Create element | document.createElement('div') |
| Remove element | el.remove() |
Lesson 4 Complete โ DOM Manipulation!
You can now select, modify, create, and remove HTML elements using JavaScript โ making your webpages truly dynamic!
Up next: JavaScript Events โ respond to clicks, keyboard presses, and more! โก
Sign up for free to track which lessons you've completed and get learning reminders.