JavaScript DOM Manipulation
The Complete Beginner to Advanced Guide with Practical Example
Table of Contents
1. What is the DOM
2. Why DOM Manipulation Matters
3. Selecting Elements
4. Changing Content
5. Modifying Styles
6. Creating Elements
7. Handling Events
8. DOM Traversal
9. Mini Project — To-Do List
10. Common Beginner Mistakes
11. Best Practices
12. Conclusion
Introduction — Why Should You Care About DOM Manipulation?
Have you ever clicked a button on a website and watched a pop-up appear out of nowhere? Or typed into a search bar and seen suggestions drop down instantly — without the page refreshing? That is DOM Manipulation at work, and by the end of this guide, you will know exactly how to build those kinds of experiences yourself.
Here is the core problem: plain HTML is static. It is like a printed flyer. It looks nice, but it does nothing. You cannot click a button in a flyer and have it change color. You cannot type into a flyer and see something updated. For a website to be truly interactive — to respond, react, and change — you need JavaScript and the power of the DOM.
Think of your HTML page as a house. The DOM is the house's floor plan, and JavaScript is the renovation crew. With JavaScript, you can knock down walls, add new rooms, repaint the walls, or even tear the whole thing down and rebuild it — all while people are living in it (i.e., while the user is on the page).
💡 By the end of this guide, you will be able to: select any element on a page, change content and styles dynamically, create and delete elements, handle user events, and build a working mini-project from scratch.
🌳 What is the DOM?
DOM stands for Document Object Model. That sounds intimidating, but let us break it down word by word.
- Document — the HTML page loaded in the browser
- Object — JavaScript represents everything as objects (think of objects as labeled boxes holding information)
- Model — a structured, organized representation of the page
When your browser loads an HTML file, it does not just display it as text. Instead, it reads every tag — every <div>, every <p>, every <button> — and builds a tree structure in memory. This tree is the DOM. Each HTML tag becomes a node in the tree.
Notice how the elements are nested — just like folders inside folders on your computer. The <html> tag is the root (the top of the tree), and everything else branches out from it. JavaScript can navigate this tree and interact with any node.
🔑 Key Insight: The DOM is not the HTML file. It is a live, in-memory representation of the page. When you change the DOM with JavaScript, the page updates instantly — without reloading.
💡 Why DOM Manipulation is Important
You might be thinking: I can style things with CSS, so why do I need JavaScript to change styles? Here is why DOM manipulation is essential — it is the engine behind nearly everything you see on modern websites.
- Changing Text Dynamically — showing a user’s name after they log in, updating a score, and displaying an error message.
- Creating Elements on the Fly — adding a new comment to a list, generating product cards from a database.
- Form Validation — checking if an email address is valid before the form is submitted.
- Dynamic UI Updates — toggling a dark/light mode, showing a modal, expanding a dropdown menu
- Games and Animations — building interactive browser games, progress bars, and transitions
Every time you see content on a webpage change without the page refreshing, DOM manipulation is happening behind the scenes. It is the bridge between static HTML and dynamic, living web experiences.
Selecting Elements in JavaScript
Before you can change anything on a page, you need to grab it — like picking up a piece of furniture before you can move it. JavaScript gives you several tools to do exactly that.
1. getElementById()
This is the simplest and most common method. It grabs exactly one element by its unique id attribute.
<! — HTML →
<h1 id=”title”>Welcome!</h1>
// JavaScript
const title = document.getElementById(“title”);
console.log(title); // Logs the <h1> element
📌 Think of an id like a social security number — it must be unique on the page. Only one element should have a given id.
Code (HTML + JS)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>getElementById Example</title>
<style>
body {
font-family: Arial;
text-align: center;
margin-top: 50px;
}
button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
</style>
</head>
<body>
<!-- Heading with unique ID -->
<h1 id="title">Welcome!</h1>
<!-- Button to trigger JavaScript -->
<button onclick="changeText()"> Click Me </button>
<script>
// Function that runs when button is clicked
function changeText() {
// Step 1: Select element using getElementById
let heading = document.getElementById("title");
// Step 2: Change the text content
heading.innerText = "Hello Students! 👋";
// Step 3: Change style dynamically
heading.style.color = "blue";
}
</script>
</body>
</html>Step 1: HTML Element
<h1 id="title">Welcome!</h1>id="title"→ unique identifier- JavaScript isi naam se element ko pakadta hai
🔹 Step 2: Select Element in JS
let heading = document.getElementById("title");- Browser document me se element nikalta hai
headingvariable me store hota hai
🔹 Step 3: Change Content
heading.innerText = "Hello Students!";- Text replace ho jata hai
🔹 Step 4: Change CSS
heading.style.color = "blue";- Styling dynamically change hoti hai
🎯 Output Behavior
- Page load → “Welcome!”
- Button click → “Hello Students! 👋” (blue color)
2. getElementsByClassName()
This grabs all elements that share a class name. Notice it returns a collection (like a list), not a single element.
<! — HTML →
<p class=”intro”>Paragraph one</p>
<p class=”intro”>Paragraph two</p>
// JavaScript
const intros = document.getElementsByClassName(“intro”);
console.log(intros[0]); // First paragraph
console.log(intros[1]); // Second paragraph
Full Code (HTML + JS)
<!DOCTYPE html>
<html>
<head>
<title>Attendance Example</title>
</head>
<body>
<h2>📋 Student Attendance</h2>
<!-- Same class for all students -->
<p class="student">Rahul - Absent ❌</p>
<p class="student">Priya - Absent ❌</p>
<p class="student">Aman - Absent ❌</p>
<!-- Button -->
<button onclick="markPresent()">Mark All Present</button>
<script>
function markPresent() {
// Select all students
let students = document.getElementsByClassName("student");
// Loop through all
for (let i = 0; i < students.length; i++) {
students[i].innerText = "Present ✅";
students[i].style.color = "green";
}
}
</script>
</body>
</html>Explanation (getElementsByClassName)
🔹 1. HTML Structure
<p class="student">Rahul - Absent ❌</p>class="student"→ The same class is used for multiple elements- This means all students are part of one group
🔹 2. Select Elements in JavaScript
let students = document.getElementsByClassName("student");- This returns multiple elements
- Type → HTMLCollection (like a list/array)
- Not a single element, but a collection
🔹 3. Access Individual Elements
students[0]; // First student
students[1]; // Second student- Use the index to access each element
🔹 4. Loop is Required
for (let i = 0; i < students.length; i++)- Because there are multiple elements
- We need to apply changes to each one
🔹 5. Change Text
students[i].innerText = "Present ✅";- Updates the text of every student
🔹 6. Change Style
students[i].style.color = "green";- Changes the color of all elements
Step-by-Step Flow
- Select elements using the class name
- Get a collection (HTMLCollection)
- Loop through elements
- Update text
- Apply style
- 3. getElementsByTagName()
Grabs all elements with a specific HTML tag. Useful when you want to target all paragraphs or all list items at once.
// Grabs ALL <p> elements on the page
const allParagraphs = document.getElementsByTagName(“p”);
console.log(allParagraphs.length); // How many paragraphs exist
3. querySelector() — The Modern Favourite
This is the most powerful selector. It uses CSS selector syntax and returns the FIRST matching element. Think of it as using a CSS rule to grab an element.
// Selects the first element with class ‘card.’
const card = document.querySelector(“.card”);
// Selects by id (same as getElementById)
const header = document.querySelector(“#main-header”);
// Even works with complex selectors!
const btn = document.querySelector(“nav ul li button”);
Full Working Code (HTML + JS)
<!DOCTYPE html>
<html>
<head>
<title>Like Button Example</title>
<style>
body {
font-family: Arial;
text-align: center;
margin-top: 40px;
}
#main-header {
color: black;
}
.card {
border: 1px solid black;
padding: 20px;
margin: 20px auto;
width: 200px;
}
button {
padding: 10px;
cursor: pointer;
}
</style>
</head>
<body>
<!-- Header -->
<h2 id="main-header">My Post</h2>
<!-- Post Card -->
<div class="card">
📸 Beautiful Nature
</div>
<!-- Like Button -->
<button onclick="likePost()">Like ❤️</button>
<script>
function likePost() {
// Select card
let card = document.querySelector(".card");
card.style.backgroundColor = "lightpink";
// Select header
let header = document.querySelector("#main-header");
header.innerText = "You liked the post ❤️";
// Select button (first button on page)
let btn = document.querySelector("button");
btn.innerText = "Liked ❤️";
}
</script>
</body>
</html>Explanation
🔹 1. HTML Structure
Header
<h2 id="main-header">My Post</h2>- This is the title of the post
id="main-header"→ used to select it in JavaScript
Post Card
<div class="card">
📸 Beautiful Nature
</div>- Represents a post (like Instagram/Facebook)
class="card"→ used to select it
Button
<button onclick="likePost()">Like ❤️</button>- When clicked → runs the
likePost()function
🔹 2. JavaScript Function
function likePost() {- This function runs when the button is clicked
🔸 Select the Card
let card = document.querySelector(".card");- Selects the first element with class
card .means class selector
👉 Then:
card.style.backgroundColor = "lightpink";- Changes background color → gives “liked” effect
🔸 Select the Header
let header = document.querySelector("#main-header");#means ID selector- Selects the heading
👉 Then:
header.innerText = "You liked the post ❤️";- Changes heading text
🔸 Select the Button
let btn = document.querySelector("button");- Selects the first button on the page
👉 Then:
btn.innerText = "Liked ❤️";- Updates button text
🎯 Final Output Behavior
Before Click:
- Heading → My Post
- Card → Normal
- Button → Like ❤️
After Click:
- Heading → You liked the post ❤️
- Card → Light pink background
- Button → Liked ❤️
💡 Key Concept
👉 querySelector():
- Uses CSS selectors (
.class,#id,tag) - Always selects the FIRST matching element
4. querySelectorAll() — Select Multiple Elements
Just like querySelector, but returns ALL matching elements as a NodeList. You can loop over them with forEach.
// Get all buttons with class “action-btn”
const buttons = document.querySelectorAll(“.action-btn”);
// Loop over them
buttons.forEach(button => {
console.log(button.textContent);
});
Full Working Code (HTML + JS)
<!DOCTYPE html>
<html>
<head>
<title>querySelectorAll Example</title>
<style>
body {
font-family: Arial;
text-align: center;
margin-top: 30px;
}
.card {
border: 1px solid black;
padding: 15px;
margin: 10px auto;
width: 250px;
}
.action-btn {
padding: 5px 10px;
margin-top: 10px;
cursor: pointer;
}
</style>
</head>
<body>
<h2>📱 Social Media Feed</h2>
<!-- Post 1 -->
<div class="card">
📸 Nature Photo
<br>
<button class="action-btn">Like ❤️</button>
</div>
<!-- Post 2 -->
<div class="card">
🍔 Food Post
<br>
<button class="action-btn">Like ❤️</button>
</div>
<!-- Post 3 -->
<div class="card">
🏖️ Travel Post
<br>
<button class="action-btn">Like ❤️</button>
</div>
<!-- Button to like all -->
<button onclick="likeAll()">Like All Posts</button>
<script>
function likeAll() {
// 1️⃣ Select ALL buttons
let buttons = document.querySelectorAll(".action-btn");
// 2️⃣ Select ALL cards
let cards = document.querySelectorAll(".card");
// 3️⃣ Loop through buttons
buttons.forEach(function(button) {
button.innerText = "Liked ❤️";
});
// 4️⃣ Loop through cards
cards.forEach(function(card) {
card.style.backgroundColor = "lightyellow";
});
}
</script>
</body>
</html>Expert Explanation (Student-Friendly)
🔹 1. Selecting Multiple Elements
let buttons = document.querySelectorAll(".action-btn");- Selects ALL elements with class
action-btn - Returns a NodeList (like array)
- Unlike
querySelector()→ not just one, but all elements
🔹 2. Loop Using forEach
buttons.forEach(function(button) {forEach()runs for each element- Cleaner than
for loop(modern JS)
🔹 3. Update Each Element
button.innerText = "Liked ❤️";- Changes text of every button
🔹 4. Same for Cards
let cards = document.querySelectorAll(".card");- Select all posts
- Apply style to all
🎯 Output Behavior
Before Click:
- All buttons → “Like ❤️”
- Cards → Normal
After Click:
- All buttons → “Liked ❤️”
- All cards → Highlighted
⚡ Key Difference
Best Practice: In modern JavaScript, use querySelector and querySelectorAll for almost everything. They are the most flexible and readable.
✏️ Changing Content in the DOM
Once you have selected an element, you can read or change its content. There are three main properties to know:
innerText
Sets or gets the visible text content of an element. It respects CSS — if text is hidden with display: none, innerText will not include it.
means innerText gets or changes the visible text inside an HTML element.
It only shows the text that users can actually see on the webpage.
If some text is hidden using CSS (for example display: none), innerText will ignore that hidden text.
<p id=”greeting”>Hello!</p>
const p = document.getElementById(“greeting”);
console.log(p.innerText); // “Hello!”
p.innerText = “Hello, JavaScript!”;
// The page now shows: Hello, JavaScript!
Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>innerText Example</title>
<style>
.hidden-text {
display: none; /* This text will be hidden */
}
</style>
</head>
<body>
<!-- Visible text -->
<p id="greeting">Hello!</p>
<!-- Hidden text (will NOT be read by innerText) -->
<p id="hidden" class="hidden-text">This is hidden text</p>
<button onclick="changeText()">Change Text</button>
<button onclick="showText()">Show innerText</button>
<script>
// Select the paragraph element
const p = document.getElementById("greeting");
function showText() {
// Get visible text only
console.log("Visible Text:", p.innerText);
}
function changeText() {
// Change visible text
p.innerText = "Hello, JavaScript!";
}
</script>
</body>
</html>📘 Explanation
🔹 What is innerText?
innerTextgets or sets only the visible text inside an element.- It ignores hidden content (like
display: none).
🔹 How it works in this example:
1. Getting text
console.log(p.innerText);👉 Output: "Hello!"
✔ Only visible text is shown
2. Changing text
p.innerText = "Hello, JavaScript!"👉 The webpage updates to:
Hello, JavaScript!3. Hidden text behavior
<p class="hidden-text">This is hidden text</p>- Because of
display: none - ❌
innerTextwill NOT read this text
🎯 Key Points (Exam Ready)
innerText→ works with visible content only- Respects CSS (like
display: none) - Used for:
- Updating UI text
- Reading user-visible content
textContent
Similar to innerText, but it grabs ALL text content, including hidden text. It is slightly faster and preferred for programmatic use when you do not need CSS awareness.
const title = document.querySelector(“h1”);
title.textContent = “New Heading Text”;
innerHTML
This is the powerful one — it can read or set HTML tags, not just text. You can inject entire HTML structures with it.
Full Example: HTML + JavaScript using innerHTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>innerHTML Example</title>
<style>
body{
font-family: Arial, sans-serif;
background:#f5f5f5;
padding:40px;
}
#info-box{
background:white;
padding:20px;
border-radius:8px;
box-shadow:0 4px 10px rgba(0,0,0,0.1);
width:300px;
}
button{
margin-top:15px;
padding:10px 16px;
border:none;
background:#007bff;
color:white;
border-radius:5px;
cursor:pointer;
}
button:hover{
background:#0056b3;
}
</style>
</head>
<body>
<h2>JavaScript innerHTML Example</h2>
<div id="info-box">
Click the button to load user info.
</div>
<button onclick="showInfo()">Load Info</button>
<script>
function showInfo(){
const box = document.querySelector("#info-box");
/* Setting HTML content */
box.innerHTML =
"<strong>Name:</strong> Alex <br> <em>Role:</em> Developer";
}
</script>
</body>
</html>What Happens in This Code
Step 1 — Select the element
const box = document.querySelector("#info-box");JavaScript selects the <div> where the content will be inserted.
Step 2 — Insert HTML content
box.innerHTML =
"<strong>Name:</strong> Alex <br> <em>Role:</em> Developer";This inserts HTML tags, not just text.
Output on page:
Name: Alex
Role: Developer- Name appears bold
- Role appears italic
Important Security Warning
Using innerHTML User input can cause Cross-site scripting.
Example of dangerous code:
box.innerHTML = userInput;If a user enters:
<script>alert("Hacked!")</script>The script will run on your website.
Safer Alternative
If you only want text, use:
box.textContent = userInput;This prevents malicious scripts from executing.
⚠️ Warning: Never use innerHTML with user-provided data directly. Injecting untrusted HTML can open your site to cross-site scripting (XSS) attacks. For plain text, always prefer textContent.
To avoid security risks like Cross-site scripting, you should not insert user data with innerHTML.
Instead, use textContent the DOM when working with JavaScript.
Below is a safer modified version of your code.
Safe Version (No Security Risk)
Full HTML + JavaScript Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Safe DOM Example</title>
<style>
body{
font-family: Arial, sans-serif;
background:#f5f5f5;
padding:40px;
}
#info-box{
background:white;
padding:20px;
border-radius:8px;
box-shadow:0 4px 10px rgba(0,0,0,0.1);
width:320px;
}
button{
margin-top:15px;
padding:10px 16px;
border:none;
background:#007bff;
color:white;
border-radius:5px;
cursor:pointer;
}
button:hover{
background:#0056b3;
}
</style>
</head>
<body>
<h2>Safe JavaScript Content Example</h2>
<div id="info-box">
Click the button to load user info.
</div>
<button onclick="showInfo()">Load Info</button>
<script>
function showInfo(){
const box = document.querySelector("#info-box");
/* Safe content insertion */
const name = "Alex";
const role = "Developer";
/* Clear old content */
box.textContent = "";
/* Create elements safely */
const nameLine = document.createElement("p");
nameLine.textContent = "Name: " + name;
const roleLine = document.createElement("p");
roleLine.textContent = "Role: " + role;
/* Append elements */
box.appendChild(nameLine);
box.appendChild(roleLine);
}
</script>
</body>
</html>Why This Version is Safe
Instead of:
innerHTML = "<strong>Name:</strong> Alex"We use:
textContent
createElement()
appendChild()These methods treat content as plain text, so scripts cannot execute.
Output
When the button is clicked:
Name: Alex
Role: DevelopeNo HTML injection is possible.
Best Practice
Use:
textContentcreateElementappendChild
Avoid using innerHTML with user input.
Quick Comparison: innerText vs textContent vs innerHTML
- innerText — visible text only, CSS-aware, human-readable
- textContent — all text, including hidden, fast, no HTML
- innerHTML — full HTML content, can inject tags, use carefully
🎨 Changing Styles Using JavaScript
You can modify any CSS property on any element directly from JavaScript. The pattern is simple: element.style.propertyName = ‘value’.
📌 Note: CSS properties with hyphens (like background-color) become camelCase in JavaScript (backgroundColor). This is because hyphens are not valid in JavaScript property names.
Direct Style Changes
const box = document.querySelector(“.box”);
// Change background color
box.style.backgroundColor = “coral”;
// Change font size
box.style.fontSize = “24px”;
// Multiple changes
box.style.padding = “20px”;
box.style.borderRadius = “10px”;
box.style.boxShadow = “0 4px 12px rgba(0,0,0,0.2)”;
Toggle a Class (Better Practice)
For larger style changes, it is cleaner to add or remove a CSS class rather than setting individual properties. Use classList for this.
// CSS (in your stylesheet)
.highlight {
background-color: yellow;
font-weight: bold;
border: 2px solid orange;
}
// JavaScript
const para = document.querySelector(“p”);
para.classList.add(“highlight”); // Adds the class
para.classList.remove(“highlight”); // Removes it
para.classList.toggle(“highlight”); // Adds if absent, removes if present
Full Example: HTML + CSS + JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript classList Example</title>
<style>
/* ===== Basic page styling ===== */
body{
font-family: Arial, sans-serif;
padding:40px;
background:#f4f4f4;
}
/* ===== Paragraph styling ===== */
p{
font-size:18px;
padding:10px;
}
/* ===== Highlight class (CSS class we will add/remove) ===== */
.highlight{
background-color: yellow; /* changes background color */
font-weight: bold; /* makes text bold */
border: 2px solid orange; /* adds border around text */
padding:10px;
}
button{
margin:5px;
padding:8px 14px;
cursor:pointer;
}
</style>
</head>
<body>
<h2>JavaScript classList Demo</h2>
<!-- Paragraph we will modify -->
<p id="demoText">
This paragraph will change style when you press the buttons.
</p>
<!-- Buttons to trigger different class operations -->
<button onclick="addHighlight()">Add Highlight</button>
<button onclick="removeHighlight()">Remove Highlight</button>
<button onclick="toggleHighlight()">Toggle Highlight</button>
<script>
/* Select the paragraph element from the DOM */
const para = document.querySelector("#demoText");
/* ==========================
Function 1: Add CSS Class
========================== */
function addHighlight(){
// Adds the CSS class "highlight" to the paragraph
// Result: background becomes yellow + bold text
para.classList.add("highlight");
}
/* ==========================
Function 2: Remove CSS Class
========================== */
function removeHighlight(){
// Removes the CSS class "highlight"
// Result: paragraph returns to normal style
para.classList.remove("highlight");
}
/* ==========================
Function 3: Toggle CSS Class
========================== */
function toggleHighlight(){
// If class exists → remove it
// If class does NOT exist → add it
para.classList.toggle("highlight");
}
</script>
</body>
</html>What Each Function Does
1️⃣ classList.add()
para.classList.add("highlight");✔ Adds the CSS class
✔ Applies highlight styling
Result:
Yellow background
Bold text
Orange border2️⃣ classList.remove()
para.classList.remove("highlight");✔ Removes the CSS class
✔ Paragraph returns to default style.
3️⃣ classList.toggle()
para.classList.toggle("highlight");✔ If class exists → remove it
✔ If class doesn’t exist → add it
This is commonly used for:
- Dark mode
- Menu toggle
- UI state changes
Simple Visual Flow
Normal Paragraph
↓
Add Highlight
↓
Yellow + Bold + Border
↓
Remove Highlight
↓
Back to Normal✅ One-line definition
classList allows JavaScript to dynamically add, remove, or toggle CSS classes on HTML elements.
🏗️ Creating and Adding Elements
You are not limited to working with elements that already exist in the HTML. You can build brand new elements from scratch and insert them anywhere on the page.
Step-by-Step: Creating a New Element
- Create the element with createElement()
- Add content or attributes to it
- Insert it into the DOM with appendChild() or prepend()
// Step 1: Create a new <li> element
const newItem = document.createElement(“li”);
// Step 2: Give it some text
newItem.textContent = “Buy groceries”;
// Step 3: Add a class to style it
newItem.classList.add(“todo-item”);
// Step 4: Find the existing list and append to it
const list = document.querySelector(“#todo-list”);
list.appendChild(newItem);
// The new <li> now appears at the END of the list
prepend() — Add to the Beginning
// This adds the element at the START of the list
list.prepend(newItem);
remove() — Delete an Element
// Remove an element entirely from the page
const oldItem = document.querySelector(“.old-news”);
oldItem.remove();
// That element is now gone from the DOM
Full Example (HTML + CSS + JavaScript)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DOM Element Creation Example</title>
<style>
/* ===== Page Styling ===== */
body{
font-family: Arial, sans-serif;
background:#f4f4f4;
padding:40px;
}
/* ===== Todo List Styling ===== */
ul{
list-style-type:none;
padding:0;
}
/* Styling for list items */
.todo-item{
background:#ffffff;
padding:10px;
margin:8px 0;
border-left:5px solid #007bff;
box-shadow:0 2px 6px rgba(0,0,0,0.1);
}
/* Old news item (for remove example) */
.old-news{
background:#ffe5e5;
padding:10px;
margin:8px 0;
border-left:5px solid red;
}
button{
margin:5px;
padding:8px 14px;
cursor:pointer;
}
</style>
</head>
<body>
<h2>JavaScript DOM Element Creation Demo</h2>
<!-- Existing List -->
<ul id="todo-list">
<li class="todo-item">Read a book</li>
<li class="todo-item">Complete homework</li>
</ul>
<br>
<!-- Example element that will be removed -->
<p class="old-news">This is outdated news.</p>
<!-- Buttons to trigger JavaScript actions -->
<button onclick="addItemEnd()">Add Item (Append)</button>
<button onclick="addItemStart()">Add Item (Prepend)</button>
<button onclick="removeNews()">Remove Old News</button>
<script>
/* ==============================
Function 1: Append Item
Adds new item at END of list
============================== */
function addItemEnd(){
// Step 1: Create a new <li> element
const newItem = document.createElement("li");
// Step 2: Add text inside the element
newItem.textContent = "Buy groceries";
// Step 3: Add a CSS class to style it
newItem.classList.add("todo-item");
// Step 4: Find the existing list
const list = document.querySelector("#todo-list");
// Step 5: Append the new item to the END of the list
list.appendChild(newItem);
}
/* ==============================
Function 2: Prepend Item
Adds new item at START of list
============================== */
function addItemStart(){
// Create new list item
const newItem = document.createElement("li");
// Add text
newItem.textContent = "Morning exercise";
// Add class for styling
newItem.classList.add("todo-item");
// Select list
const list = document.querySelector("#todo-list");
// Insert at beginning of list
list.prepend(newItem);
}
/* ==============================
Function 3: Remove Element
Deletes element from the page
============================== */
function removeNews(){
// Select the element with class "old-news"
const oldItem = document.querySelector(".old-news");
// Remove it from the DOM
oldItem.remove();
}
</script>
</body>
</html>Step-by-Step Explanation
1️⃣ Create an Element
const newItem = document.createElement("li");This creates a new <li> element in memory.
2️⃣ Add Text Content
newItem.textContent = "Buy groceries";Adds text inside the element.
Result:
<li>Buy groceries</li>3️⃣ Add a CSS Class
newItem.classList.add("todo-item");This applies styling from CSS.
4️⃣ Append Element to DOM
list.appendChild(newItem);Adds the element to the end of the list.
Example result:
Read a book
Complete homework
Buy groceries5️⃣ Prepend Element
list.prepend(newItem);Adds the element to the beginning of the list.
Example result:
Morning exercise
Read a book
Complete homework6️⃣ Remove an Element
oldItem.remove();Deletes the element completely from the page.
Before:
This is outdated newsAfter clicking the button:
(Element disappears)Simple DOM Flow
Create Element
↓
Add Text / Class
↓
Insert into DOM
(appendChild / prepend)
↓
Remove if needed✅ Short Definition
createElement()→ creates a new HTML elementappendChild()→ adds element at endprepend()→ adds element at the beginningremove()→ deletes element from DOM
💡 Pro Tip: You can also use insertBefore(), after(), and before() for precise placement. But for most beginners, appendChild and prepend are all you need.
⚡ Handling Events — Making Things Interactive
This is the most exciting section. Events are things that happen on a webpage — a user clicking a button, hovering over an image, typing in a field, or resizing the window. JavaScript listens for these events and responds to them.
Method 1: The onclick Attribute (Quick but Limited)
<! — HTML →
<button onclick=”alert(‘You clicked me!’)”>Click Here</button>
This works, but mixing JavaScript directly inside HTML is not great practice. It gets messy fast. There is a better way.
Method 2: addEventListener() — The Professional Way
addEventListener lets you attach any number of event listeners to any element. It keeps your JavaScript separate from your HTML, which is cleaner and more maintainable.
// Syntax
element.addEventListener(‘eventType’, callbackFunction);
// Example: Button changes text on click
Get Pranshi Verma’s stories in your inbox
Join Medium for free to get updates from this writer.
const btn = document.querySelector(“#my-btn”);
const msg = document.querySelector(“#message”);
btn.addEventListener(‘click’, function() {
msg.textContent = “You clicked the button!”;
msg.style.color = “green”;
});
Example 1: Button Changes Color
const colorBtn = document.querySelector(“#color-btn”);
const box = document.querySelector(“#color-box”);
colorBtn.addEventListener(‘click’, function() {
const colors = [‘tomato’, ‘steelblue’, ‘goldenrod’, ‘seagreen’];
const random = Math.floor(Math.random() * colors.length);
box.style.backgroundColor = colors[random];
});
This program changes the background color of a box randomly when a button is clicked.
Full Code (HTML + CSS + JavaScript)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Random Color Button</title>
<style>
/* ===== Page Styling ===== */
body{
font-family: Arial, sans-serif;
text-align:center;
background:#f4f4f4;
padding:40px;
}
/* ===== Color Box ===== */
#color-box{
width:250px;
height:150px;
background:lightgray;
margin:20px auto;
border-radius:8px;
display:flex;
align-items:center;
justify-content:center;
font-weight:bold;
}
/* ===== Button Styling ===== */
button{
padding:10px 18px;
border:none;
background:#007bff;
color:white;
font-size:16px;
border-radius:5px;
cursor:pointer;
}
button:hover{
background:#0056b3;
}
</style>
</head>
<body>
<h2>Random Color Changer</h2>
<!-- Box whose color will change -->
<div id="color-box">
Click the button
</div>
<!-- Button to trigger color change -->
<button id="color-btn">Change Color</button>
<script>
/* ==============================
Step 1: Select elements
============================== */
// Select the button
const colorBtn = document.querySelector("#color-btn");
// Select the box whose color will change
const box = document.querySelector("#color-box");
/* ==============================
Step 2: Add click event
============================== */
colorBtn.addEventListener('click', function() {
/* Array of colors */
const colors = ['tomato', 'steelblue', 'goldenrod', 'seagreen'];
/* Generate random number
Math.random() → random value between 0 and 1
Multiply by array length
Math.floor() removes decimal */
const random = Math.floor(Math.random() * colors.length);
/* Change box background color */
box.style.backgroundColor = colors[random];
});
</script>
</body>
</html>
Step-by-Step Explanation
1️⃣ Select Elements from the DOM
const colorBtn = document.querySelector("#color-btn");
const box = document.querySelector("#color-box");This selects:
- the button
- the color box
from the webpage.
2️⃣ Add Click Event
colorBtn.addEventListener('click', function() {This means:
👉 When the button is clicked
👉 Run the function inside it.
3️⃣ Create Color List
const colors = ['tomato', 'steelblue', 'goldenrod', 'seagreen'];An array of colors is created.
Example colors:
tomato
steelblue
goldenrod
seagreen4️⃣ Generate Random Number
const random = Math.floor(Math.random() * colors.length);Explanation:
FunctionPurposeMath.random()generates a random numbercolors.lengthnumber of colorsMath.floor()removes decimal
Example result:
0
1
2
35️⃣ Apply Random Color
box.style.backgroundColor = colors[random];This changes the background color of the box.
Example output:
Click button → box becomes tomato
Click again → box becomes seagreen
Click again → box becomes steelblueSimple Flow
Button Click
↓
Generate Random Number
↓
Pick Random Color
↓
Apply Color to Box✅ One-line concept
addEventListener() listens for user actions (like clicks) and executes JavaScript code when the event occurs.
Example 2: Simple Click Counter
let count = 0;
const countBtn = document.querySelector(“#count-btn”);
const countDisplay = document.querySelector(“#count-display”);
countBtn.addEventListener(‘click’, function() {
count++;
countDisplay.textContent = “Clicks: “ + count;
});
Full Code (HTML + CSS + JavaScript)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Click Counter</title>
<style>
/* ===== Page Styling ===== */
body{
font-family: Arial, sans-serif;
text-align:center;
background:#f4f4f4;
padding:40px;
}
/* Counter display box */
#count-display{
font-size:24px;
font-weight:bold;
margin:20px;
}
/* Button styling */
button{
padding:10px 18px;
border:none;
background:#007bff;
color:white;
font-size:16px;
border-radius:5px;
cursor:pointer;
}
button:hover{
background:#0056b3;
}
</style>
</head>
<body>
<h2>Simple Click Counter</h2>
<!-- Display area where click count will appear -->
<div id="count-display">
Clicks: 0
</div>
<!-- Button user will click -->
<button id="count-btn">
Click Me
</button>
<script>
/* ============================
Step 1: Create a counter variable
============================ */
// This variable stores the number of clicks
let count = 0;
/* ============================
Step 2: Select DOM elements
============================ */
// Select the button
const countBtn = document.querySelector("#count-btn");
// Select the display area
const countDisplay = document.querySelector("#count-display");
/* ============================
Step 3: Add click event
============================ */
countBtn.addEventListener('click', function() {
/* Increase count value by 1 */
count++;
/* Update the display text */
countDisplay.textContent = "Clicks: " + count;
});
</script>
</body>
</html><title>Simple Click Counter</title>
<style>
/* ===== Page Styling ===== */
body{
font-family: Arial, sans-serif;
text-align:center;
background:#f4f4f4;
padding:40px;
}
/* Counter display box */
#count-display{
font-size:24px;
font-weight:bold;
margin:20px;
}
/* Button styling */
button{
padding:10px 18px;
border:none;
background:#007bff;
color:white;
font-size:16px;
border-radius:5px;
cursor:pointer;
}
button:hover{
background:#0056b3;
}
</style>
</head>
<body>
<h2>Simple Click Counter</h2>
<!-- Display area where click count will appear -->
<div id="count-display">
Clicks: 0
</div>
<!-- Button user will click -->
<button id="count-btn">
Click Me
</button>
<script>
/* ============================
Step 1: Create a counter variable
============================ */
// This variable stores the number of clicks
let count = 0;
/* ============================
Step 2: Select DOM elements
============================ */
// Select the button
const countBtn = document.querySelector("#count-btn");
// Select the display area
const countDisplay = document.querySelector("#count-display");
/* ============================
Step 3: Add click event
============================ */
countBtn.addEventListener('click', function() {
/* Increase count value by 1 */
count++;
/* Update the display text */
countDisplay.textContent = "Clicks: " + count;
});
</script>
</body>
</html>Step-by-Step Explanation
1️⃣ Create Counter Variable
let count = 0;This variable stores the number of button clicks.
Initial value:
02️⃣ Select Elements from the DOM
const countBtn = document.querySelector("#count-btn");
const countDisplay = document.querySelector("#count-display");These lines select:
- the button
- the text display area
from the webpage.
3️⃣ Add Click Event Listener
countBtn.addEventListener('click', function() {This means:
👉 When the user clicks the button
👉 Run the function inside it.
4️⃣ Increase the Counter
count++;This is shorthand for:
count = count + 1So each click increases the number.
Example:
Click 1 → count = 1
Click 2 → count = 2
Click 3 → count = 35️⃣ Update the Display
countDisplay.textContent = "Clicks: " + count;This updates the text shown on the page.
Example output:
Clicks: 1
Clicks: 2
Clicks: 3Program Flow
User clicks button
↓
Event listener runs
↓
count increases by 1
↓
Display updates✅ Concept Used
querySelector()→ selects elementsaddEventListener()→ listens for user actionstextContent→ updates text on page- variable
count→ stores click value
Common Event Types to Know
- ‘click’ — user clicks an element
- ‘mouseover’ / ‘mouseout’ — mouse enters or leaves an element
- ‘keydown’ / ‘keyup’ — user presses or releases a key
- ‘submit’ — a form is submitted
- ‘input’ — user types into an input field (fires on every keystroke)
- ‘change’ — value of an input changes and loses focus
- ‘load’ — the page fully loads
🗺️ DOM Traversal — Navigating the Tree
Sometimes you do not know the exact element you need up front. Instead, you have one element and need to navigate to its relatives — its parent, children, or siblings. This is called DOM traversal, and it works just like navigating a family tree.
parentElement — Go Up One Level
const item = document.querySelector(“.list-item”);
const parent = item.parentElement;
// parent is now the <ul> or <ol> containing the item
console.log(parent.tagName); // “UL”
children — Get All Direct Children
const list = document.querySelector(“ul”);
const items = list.children;
// items is an HTMLCollection of all <li> elements
console.log(items.length); // How many list items
console.log(items[0].textContent); // First item text
nextElementSibling & previousElementSibling
const secondItem = document.querySelector(“li:nth-child(2)”);
const next = secondItem.nextElementSibling;
// Gets the <li> that comes AFTER the second item
const prev = secondItem.previousElementSibling;
// Gets the <li> that comes BEFORE the second item
🧭 Think of DOM traversal like directions:
🛠️ Real Mini Project: Interactive To-Do List
Let us put everything together! We will build a simple To-Do List app using only HTML and JavaScript. This project will use: creating elements, handling events, reading input values, and removing elements.
The HTML Structure
<!DOCTYPE html>
<html lang=’en’>
<head>
<title>To-Do List</title>
<style>
body { font-family: Arial, sans-serif; max-width: 500px; margin: 40px auto; padding: 0 20px; }
.todo-item { display: flex; justify-content: space-between; padding: 10px;
margin: 8px 0; background: #f3f4f6; border-radius: 8px; }
.delete-btn { background: #ef4444; color: white; border: none;
padding: 4px 10px; border-radius: 4px; cursor: pointer; }
input { width: 70%; padding: 8px; border: 1px solid #d1d5db; border-radius: 6px; }
button#add-btn { padding: 8px 16px; background: #3b82f6; color: white;
border: none; border-radius: 6px; cursor: pointer; }
</style>
</head>
<body>
<h1>My To-Do List</h1>
<div>
<input type=’text’ id=’task-input’ placeholder=’Add a new task…’ />
<button id=’add-btn’>Add</button>
</div>
<ul id=’task-list’></ul>
<script src=’app.js’></script>
</body>
</html>
The JavaScript (app.js)
// Step 1: Grab our elements
const input = document.getElementById(‘task-input’);
const addBtn = document.getElementById(‘add-btn’);
const taskList = document.getElementById(‘task-list’);
// Step 2: Listen for the Add button click
addBtn.addEventListener(‘click’, function() {
// Step 3: Read the input value
const taskText = input.value.trim();
// Step 4: Validate — do not add empty tasks
if (taskText === ‘’) {
alert(‘Please enter a task!’);
return;
}
// Step 5: Create a new list item
const li = document.createElement(‘li’);
li.classList.add(‘todo-item’);
// Step 6: Add the task text
const span = document.createElement(‘span’);
span.textContent = taskText;
// Step 7: Create a delete button
const deleteBtn = document.createElement(‘button’);
deleteBtn.textContent = ‘Delete’;
deleteBtn.classList.add(‘delete-btn’);
// Step 8: Delete button removes the item
deleteBtn.addEventListener(‘click’, function() {
li.remove();
});
// Step 9: Assemble the list item
li.appendChild(span);
li.appendChild(deleteBtn);
// Step 10: Add it to the list
taskList.appendChild(li);
// Step 11: Clear the input
input.value = ‘’;
input.focus();
});
// Bonus: Allow pressing Enter to add a task
input.addEventListener(‘keydown’, function(event) {
if (event.key === ‘Enter’) {
addBtn.click();
}
});
There it is — a fully functional To-Do List built with pure DOM manipulation. No frameworks, no libraries, just HTML and JavaScript. Every concept in this guide came together to build something real.
JavaScript DOM Manipulation — Examples
Example 1: DOM Manipulation using getElementById()
This example shows how JavaScript selects an element using its id and changes its text when a button is clicked.
Complete Code (HTML + JavaScript with Comments)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DOM Manipulation Example</title>
</head>
<body>
<!-- Paragraph element with id="demo" -->
<!-- JavaScript will access this element using its ID -->
<p id="demo">Hello Students</p>
<!-- Button element -->
<!-- When user clicks the button, changeText() function will run -->
<button onclick="changeText()">Click Me</button>
<script>
// This function will run when the button is clicked
function changeText() {
// Step 1: Select the element using its ID
// document = represents the whole HTML page
// getElementById("demo") finds the element with id="demo"
let element = document.getElementById("demo");
// Step 2: Change the text inside the paragraph
// innerText updates the visible text of the element
element.innerText = "DOM Manipulation is Easy!";
}
</script>
</body>
</html>How This Code Works (Step-by-Step for Students)
1️⃣ HTML creates the elements
<p id="demo">Hello Students</p>This paragraph has an id = demo, which allows JavaScript to find it.
2️⃣ Button triggers JavaScript
<button onclick="changeText()">Click Me</button>When the user clicks the button:
➡ changeText() function runs.
3️⃣ JavaScript selects the element
document.getElementById("demo")This tells the browser:
👉 “Find the element whose id is demo”.
4️⃣ JavaScript changes the text
element.innerText = "DOM Manipulation is Easy!";This replaces the original text:
Hello Studentswith
DOM Manipulation is Easy!Output Flow
Initial Page
Hello Students
[Click Me]After clicking the button
DOM Manipulation is Easy!
[Click Me]Key Concept
Example 2 — DOM Manipulation using getElementsByClassName()
This example selects multiple elements that share the same class and changes their color when a button is clicked.
Complete Code (HTML + JavaScript with Comments)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DOM getElementsByClassName Example</title>
</head>
<body>
<!-- Paragraph elements with the same class name "item" -->
<!-- JavaScript will select all these elements together -->
<p class="item">Apple</p>
<p class="item">Banana</p>
<p class="item">Mango</p>
<!-- Button that calls the JavaScript function -->
<!-- When clicked, changeColor() will run -->
<button onclick="changeColor()">Change Color</button>
<script>
// Function that runs when button is clicked
function changeColor() {
// Step 1: Select all elements with class "item"
// getElementsByClassName returns a collection (array-like list)
let items = document.getElementsByClassName("item");
// Step 2: Loop through all elements in the collection
// items.length tells how many elements were selected
for (let i = 0; i < items.length; i++) {
// Step 3: Change the style of each element
// Here we change the text color to red
items[i].style.color = "red";
}
}
</script>
</body>
</html>Step-by-Step Explanation for Students
1️⃣ HTML Elements
<p class="item">Apple</p>
<p class="item">Banana</p>
<p class="item">Mango</p>All these paragraphs have the same class name = item.
This allows JavaScript to select all of them together.
2️⃣ Button Triggers JavaScript
<button onclick="changeColor()">Change Color</button>When the user clicks the button:
➡ The function changeColor() runs.
3️⃣ Selecting Elements with Class Name
let items = document.getElementsByClassName("item");This line tells the browser:
👉 “Find all elements with class item”.
It returns something like this:
[Apple Paragraph, Banana Paragraph, Mango Paragraph]4️⃣ Loop Through All Elements
for (let i = 0; i < items.length; i++)Because multiple elements are selected, we must loop through them.
items.length tells how many elements exist.
In this case:
items.length = 35️⃣ Change Style
items[i].style.color = "red";This changes the text color of each paragraph.
Result:
Apple → red
Banana → red
Mango → redOutput Before Clicking Button
Apple
Banana
Mango[Change Color]Output After Clicking the Button
Apple (red)
Banana (red)
Mango (red)[Change Color]Key Concepts Students Should Remember
Example 3 — Changing CSS Style using JavaScript DOM
This example shows how JavaScript can select an HTML element and modify its CSS properties when a button is clicked.
Complete Code (HTML + JavaScript with Comments)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DOM Style Manipulation Example</title>
<style>
/* Initial style for the paragraph */
#box{
font-size:20px;
}
</style>
</head>
<body>
<!-- Paragraph element -->
<!-- This element has id="box" so JavaScript can select it easily -->
<p id="box">Style Me</p>
<!-- Button element -->
<!-- When the user clicks the button, the styleText() function will run -->
<button onclick="styleText()">Apply Style</button>
<script>
// Function that will run when the button is clicked
function styleText() {
// Step 1: Select the element using its ID
// document represents the entire HTML page
// getElementById("box") finds the element with id="box"
let element = document.getElementById("box");
// Step 2: Change CSS styles using JavaScript
// element.style allows us to modify CSS properties
element.style.color = "white"; // Changes text color
element.style.background = "blue"; // Changes background color
element.style.padding = "10px"; // Adds space inside the element
element.style.borderRadius = "5px"; // Makes rounded corners
element.style.width = "150px"; // Sets width of the box
element.style.textAlign = "center"; // Aligns text in center
}
</script>
</body>
</html>Step-by-Step Explanation for Students
1️⃣ HTML Element
<p id="box">Style Me</p>This paragraph has id = box.
JavaScript will use this id to find the element.
2️⃣ Button Calls JavaScript Function
<button onclick="styleText()">Apply Style</button>When the button is clicked:
➡ styleText() function runs.
3️⃣ Selecting the Element
let element = document.getElementById("box");This tells the browser:
👉 “Find the element whose id is box”.
4️⃣ Changing CSS with JavaScript
JavaScript can modify CSS using:
element.style.property = "value";Example:
element.style.color = "white";Changes text color.
5️⃣ Multiple Style Changes
element.style.background = "blue";
element.style.padding = "10px";
element.style.borderRadius = "5px";These styles are applied immediately after clicking the button.
Output Before Clicking the Button
Style Me[Apply Style]Output After Clicking the Button
A blue box appears with white centered text.
[ Style Me ]Key Concepts for Students
Example 3 — DOM Manipulation using getElementsByTagName()
This method selects elements based on their HTML tag name.
In this example, JavaScript selects all <h2> elements and changes the first heading when a button is clicked.
Complete Code (HTML + JavaScript with Comments)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>getElementsByTagName Example</title>
</head>
<body>
<!-- Heading elements -->
<!-- All these elements use the same HTML tag <h2> -->
<h2>Student 1</h2>
<h2>Student 2</h2>
<h2>Student 3</h2>
<!-- Button that triggers the JavaScript function -->
<button onclick="changeHeading()">Change</button>
<script>
// Function runs when the button is clicked
function changeHeading() {
// Step 1: Select all <h2> elements from the document
// getElementsByTagName returns a collection (array-like list)
let headings = document.getElementsByTagName("h2");
// Step 2: Access the first heading in the collection
// Index starts from 0, so headings[0] refers to the first <h2>
headings[0].innerText = "Topper Student";
// This replaces the text "Student 1" with "Topper Student"
}
</script>
</body>
</html>Step-by-Step Explanation for Students
1️⃣ HTML Headings
<h2>Student 1</h2>
<h2>Student 2</h2>
<h2>Student 3</h2>All these elements use the same HTML tag <h2>.
2️⃣ Button Executes JavaScript
<button onclick="changeHeading()">Change</button>When the user clicks the button:
➡ The function changeHeading() runs.
3️⃣ Selecting Elements by Tag Name
let headings = document.getElementsByTagName("h2");This tells the browser:
👉 “Find all <h2> elements in the page”.
The result is something like this:
[Student 1 Heading, Student 2 Heading, Student 3 Heading]This list is called an HTMLCollection.
4️⃣ Accessing the First Element
headings[0]Array-style indexing is used:
IndexElement0Student 11Student 22Student 3
So headings[0] refers to Student 1.
5️⃣ Changing the Text
headings[0].innerText = "Topper Student";This replaces the original text:
Student 1with:
Topper StudentOutput Before Clicking Button
Student 1
Student 2
Student 3[Change]Output After Clicking the Button
Topper Student
Student 2
Student 3[Change]Key Concepts Students Should Remember
Example 4— Changing CSS with JavaScript
In this example, JavaScript selects an element and changes its text color, background color, and padding when a button is clicked.
Complete Code (HTML + JavaScript with Comments)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Change CSS with JavaScript</title>
<style>
/* Initial styling for the paragraph */
#textBox{
font-size:20px;
}
</style>
</head>
<body>
<!-- Paragraph element -->
<!-- This element has id="textBox" so JavaScript can easily select it -->
<p id="textBox">Learning JavaScript DOM</p>
<!-- Button that triggers the JavaScript function -->
<button onclick="changeStyle()">Change Style</button>
<script>
// Function that runs when the button is clicked
function changeStyle() {
// Step 1: Select the element using its ID
// document represents the entire webpage
// getElementById("textBox") finds the element with id="textBox"
let element = document.getElementById("textBox");
// Step 2: Modify CSS properties using JavaScript
// Syntax: element.style.property = "value"
element.style.color = "white"; // Changes text color
element.style.background = "green"; // Changes background color
element.style.padding = "10px"; // Adds space inside the element
element.style.borderRadius = "5px"; // Adds rounded corners
element.style.width = "220px"; // Sets width of the box
element.style.textAlign = "center"; // Aligns text to the center
}
</script>
</body>
</html>Step-by-Step Explanation for Students
1️⃣ HTML Element
<p id="textBox">Learning JavaScript DOM</p>This paragraph has an id = textBox.
JavaScript will use this id to locate the element in the DOM.
2️⃣ Button Calls JavaScript
<button onclick="changeStyle()">Change Style</button>When the user clicks the button:
➡ The changeStyle() function runs.
3️⃣ Selecting the Element
let element = document.getElementById("textBox");This tells the browser:
👉 “Find the element whose id is textBox”.
4️⃣ Changing CSS Using JavaScript
General syntax:
element.style.property = "value";Example:
element.style.color = "white";This changes the text color.
5️⃣ Applying Multiple Styles
element.style.background = "green";
element.style.padding = "10px";
element.style.borderRadius = "5px";These lines modify the element’s appearance dynamically.
Output Before Clicking Button
Learning JavaScript DOM[Change Style]Output After Clicking Button
A green box appears with white centered text.
[ Learning JavaScript DOM ]Key Concepts Students Should Remember
Common Mistakes Beginners Make
1. Running JavaScript Before the DOM Loads
// ❌ WRONG — script in <head> runs before body exists
const btn = document.getElementById(“myBtn”); // Returns null!
// ✅ CORRECT — place <script> at the end of <body>
// OR use the DOMContentLoaded event
document.addEventListener(‘DOMContentLoaded’, function() {
const btn = document.getElementById(“myBtn”); // Works!
});
2. Forgetting That getElementsByClassName Returns a Collection
// ❌ WRONG — this is a collection, not a single element
const items = document.getElementsByClassName(“item”);
items.style.color = “red”; // Error! Collections have no style property
// ✅ CORRECT — loop over the collection
Array.from(items).forEach(item => item.style.color = “red”);
3. Misspelling getElementById (capital D in Id)
// ❌ WRONG
document.getElementByID(“box”); // Capital D — throws an error!
// ✅ CORRECT
document.getElementById(“box”); // lowercase d
4. Using innerHTML When textContent is Safer
Using innerHTML with user input can introduce security vulnerabilities. If a user types <script>alert(‘hacked’)</script> and you inject it with innerHTML, you have a problem. Always sanitize or use textContent for plain text.
✅ Best Practices for DOM Manipulation
- Cache your DOM selections — if you use an element multiple times, store it in a variable instead of querying the DOM repeatedly
- Use addEventListener over inline onclick — it is cleaner, more flexible, and allows multiple listeners
- Prefer classList over direct style changes — toggling classes keeps your CSS in one place and your JS clean
- Use querySelector and querySelectorAll for consistency — no need to mix getElementById, getElementsByClassName, and getElementsByTagName
- Minimize DOM operations — every time you change the DOM, the browser may repaint the page; batch your changes when possible
- Validate user input before injecting it — never trust raw user input in innerHTML
- Place your script tags at the bottom of <body> — this ensures the DOM is fully loaded before your JS runs
🎉 Conclusion
Congratulations — you have just taken a complete journey through JavaScript DOM Manipulation, from the very basics all the way to building a real interactive project. You started by learning what the DOM actually is (a live tree of your HTML page). You then learned how to select elements, change their content and styles, create new elements, listen for user events, and navigate the DOM tree.
The most important thing to remember is this: every interactive feature you have ever used on a website — a dropdown menu, a color theme toggle, a popup dialog, a live search bar — was built using exactly these concepts. You now have the foundations to build all of those things yourself.
The best way to get comfortable with DOM manipulation is to practice. Start by modifying small things on simple pages. Then try rebuilding familiar UI components from scratch. Every line of code you write cements this knowledge deeper. You have got this.
🔑 5 Key Takeaways
- The DOM is a live, in-memory tree structure that represents your HTML page. JavaScript can read and modify this tree to create dynamic, interactive experiences.
- Use querySelector and querySelectorAll for selecting elements — they support CSS-style selectors and work consistently across all element types.
- Prefer textContent over innerHTML for plain text changes to avoid security risks, and use classList.toggle() for style changes instead of modifying individual style properties.
- addEventListener is the correct and professional way to handle user events. It keeps your JavaScript separate from your HTML and allows multiple event handlers on the same element.
- Practice is the fastest way to learn DOM manipulation. Build small projects — counters, to-do lists, theme togglers — and every concept will click into place naturally.
Tags
#JavaScript #DOMManipulation #WebDevelopment #LearnJavaScript #FrontendDevelopment #JavaScriptBeginners #HTMLAndJavaScript #querySelector #EventListeners #WebDesign




