Dom
Learn how to interact with and modify HTML elements using JavaScript — bring your webpages to life with dynamic content, styles, and interactivity.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
What You'll Learn in This Lesson
💡 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 .html file 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.
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.
📌 Method 2: getElementsByClassName
Select all elements with a specific class name. Returns an HTMLCollection (array-like object).
📌 Method 3: querySelector (Modern & Recommended)
The most versatile method — uses CSS selectors to find elements. Returns the first match .
📌 Method 4: querySelectorAll
Like querySelector , but returns all matching elements as a NodeList.
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.
🏗️ Using innerHTML (More Powerful)
Changes the HTML content inside an element. Tags are parsed and rendered.
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
🎨 Changing Styles — Making Things Beautiful
You can modify CSS styles directly using JavaScript's style property.
🖌️ Basic Styling
🎭 Multiple Styles at Once
🔄 Example: Theme Switcher
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
➖ Removing Classes
🔄 Toggling Classes
The most useful method — adds the class if it's not there, removes it if it is.
✅ Checking if a Class Exists
📝 Real-World Example: Tabs
- • 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
📦 Inserting Elements — Different Ways
🗑️ Removing Elements
📋 Example: To-Do List
🔧 Working with Attributes — The Details
Attributes are the properties you set in HTML tags, like id , src , href , data-* , etc.
🎯 Getting Attributes
✏️ Setting Attributes
🗑️ Removing Attributes
📊 Data Attributes (data-*)
Custom attributes that start with data- are perfect for storing extra information.
🚫 Common Mistakes to Avoid
❌ Mistake 1: Selecting Before DOM is Ready
❌ Mistake 2: Not Checking if Element Exists
❌ Mistake 3: Using innerHTML with User Input
❌ Mistake 4: Modifying DOM in a Loop (Slow)
✅ 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.
📚 Quick Reference Guide
🔍 Selection Methods
- getElementById(id) — Get element by ID
- querySelector(selector) — First match (CSS selector)
- querySelectorAll(selector) — All matches
- getElementsByClassName() — By class name
- getElementsByTagName() — By tag name
🏗️ Creation Methods
- createElement(tag) — Create new element
- appendChild(element) — Add as last child
- insertBefore(new, ref) — Insert before reference
- removeChild(element) — Remove child element
- element.remove() — Remove element itself
✏️ Content Methods
- textContent — Get/set text (safe)
- innerHTML — Get/set HTML (powerful)
- value — Get/set form input value
- innerText — Get/set visible text
🎨 Style & Class Methods
- element.style.property — Set inline style
- classList.add() — Add CSS class
- classList.remove() — Remove CSS class
- classList.toggle() — Toggle CSS class
- classList.contains() — Check if class exists
🔧 Attribute Methods
- getAttribute(name) — Get attribute value
- setAttribute(name, val) — Set attribute
- removeAttribute(name) — Remove attribute
- hasAttribute(name) — Check if exists
- dataset.property — Access data-* attributes
🔄 Traversal Methods
- parentElement — Get parent element
- children — Get child elements
- firstElementChild — First child
- lastElementChild — Last child
- nextElementSibling — 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
- • 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
- • 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
- • 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
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
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!
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! ⚡
Practice quiz
What does the DOM represent?
- A CSS stylesheet
- A database of users
- Your HTML page as a tree of objects JavaScript can interact with
- The browser's network requests
Answer: Your HTML page as a tree of objects JavaScript can interact with. The Document Object Model represents the page as a live tree of objects you can read and modify.
What does document.querySelector('.box') return?
- The first element matching the CSS selector
- All elements with class box
- An array of nodes
- The element's text
Answer: The first element matching the CSS selector. querySelector returns the first match for a CSS selector, or null if none is found.
Which method returns ALL matching elements as a NodeList?
- getElementById
- querySelector
- getElementByClass
- querySelectorAll
Answer: querySelectorAll. querySelectorAll returns every matching element as a NodeList.
Why is textContent safer than innerHTML for user input?
- It is faster
- It treats input as plain text, preventing XSS
- It renders HTML tags
- It validates emails
Answer: It treats input as plain text, preventing XSS. textContent escapes HTML so injected script tags display as text rather than executing — preventing XSS.
What does element.classList.toggle('open') do?
- Adds the class if absent, removes it if present
- Always adds the class
- Always removes the class
- Renames the class
Answer: Adds the class if absent, removes it if present. toggle adds the class when it is missing and removes it when present.
How do you create a new element in the DOM?
- document.newElement('div')
- document.addElement('div')
- document.createElement('div')
- new Element('div')
Answer: document.createElement('div'). document.createElement('div') creates a new, detached element you then insert into the page.
Which appends a node as the last child of a parent?
- parent.insertBefore(node)
- parent.appendChild(node)
- parent.prepend(node, null)
- parent.remove(node)
Answer: parent.appendChild(node). appendChild adds the node as the last child of the parent element.
What is the modern way to remove an element from the DOM?
- element.delete()
- element.destroy()
- element.hide()
- element.remove()
Answer: element.remove(). element.remove() removes the element itself; the older way is element.parentNode.removeChild(element).
How is the CSS property background-color written in element.style?
- background-color
- backgroundColor
- background_color
- BackgroundColor
Answer: backgroundColor. Hyphenated CSS properties become camelCase in JavaScript, so it is element.style.backgroundColor.
How do you read a data-id attribute from an element?
- element.data.id
- element.getData('id')
- element.dataset.id
- element.attributes.id
Answer: element.dataset.id. Custom data-* attributes are accessed through the dataset property, e.g. element.dataset.id.