JavaScript Series Part 3: DOM Manipulation and Events – Make Your Website Come Alive
By Sohail Shabbir · Coding & Programming · Sat Jun 06 2026
Part 3 of the JavaScript series covers DOM manipulation and events. Learn how to select HTML elements, change content, handle user clicks, and build interactive
Welcome back to the JavaScript Series! If you missed the first two parts, we covered the basics of JavaScript — variables, data types, functions, and conditionals. Now in Part 3, we are going to learn something really exciting: DOM Manipulation and Events.
This is where JavaScript becomes truly powerful. You will learn how to change what the user sees on the screen, respond to clicks and keyboard input, and make your website feel alive and interactive. By the end of this article, you will be able to build real interactive features like buttons that change content, forms that show messages, and elements that appear or disappear.
Let us get started.
What is the DOM?
DOM stands for Document Object Model. When a browser loads your HTML page, it reads all the HTML code and creates a tree-like structure in memory. This tree is called the DOM.
Think of your HTML like a family tree. The <html> tag is the grandparent. Inside it you have <head> and <body> as children. Inside <body> you have your headings, paragraphs, buttons, and so on.
JavaScript can read and change this tree. You can:
- Find any HTML element on the page
- Change its text or style
- Add or remove elements completely
- React when a user clicks, types, or moves their mouse
This is DOM Manipulation — and it is the core skill of every frontend JavaScript developer.
How to Select HTML Elements
Before you can change anything, you need to select it. JavaScript gives you several ways to do this.
1. getElementById
This is the most simple and common way. You select an element using its id attribute.
<!-- HTML -->
<h1 id="main-title">Hello World</h1>
<script>
// JavaScript
const title = document.getElementById("main-title");
console.log(title); // shows the h1 element
</script>
2. querySelector
This is a more flexible method. You can select by id, class, or tag name using CSS-style selectors.
// Select by ID
const title = document.querySelector("#main-title");
// Select by class name
const box = document.querySelector(".my-box");
// Select by tag
const firstParagraph = document.querySelector("p");
3. querySelectorAll
This selects all matching elements and returns a list of them.
// Select all paragraph tags on the page
const allParagraphs = document.querySelectorAll("p");
// Loop through them
allParagraphs.forEach(function(para) {
console.log(para.textContent);
});
How to Change HTML Content
Once you have selected an element, you can change what it shows on screen. The two most used properties are textContent and innerHTML.
textContent — Change Plain Text
Use this when you want to change or read the text inside an element. It is safe and simple.
<p id="message">Original message here</p>
<script>
const msg = document.getElementById("message");
msg.textContent = "The message has been updated!";
</script>
innerHTML — Change HTML Content
Use this when you want to insert HTML tags, not just plain text.
const box = document.querySelector(".content-box");
box.innerHTML = "<strong>This is bold text</strong> and some normal text.";
Note: Be careful with innerHTML when using user input. Never insert unfiltered user data into innerHTML — this can cause security problems called XSS (Cross-Site Scripting).
Change Styles with JavaScript
You can also change CSS styles directly from JavaScript using the style property.
const title = document.getElementById("main-title");
// Change color
title.style.color = "blue";
// Change font size
title.style.fontSize = "32px";
// Hide an element
title.style.display = "none";
// Show it again
title.style.display = "block";
Add or Remove CSS Classes
A better practice is to define your styles in CSS and then just toggle classes from JavaScript.
/* CSS */
.highlight {
background-color: yellow;
font-weight: bold;
}
/* JavaScript */
const element = document.querySelector(".my-card");
// Add a class
element.classList.add("highlight");
// Remove a class
element.classList.remove("highlight");
// Toggle — adds if not there, removes if it is
element.classList.toggle("highlight");
How to Change HTML Attributes
Attributes like src, href, placeholder, and disabled can all be changed with JavaScript.
// Change image source
const img = document.querySelector("img");
img.setAttribute("src", "new-image.jpg");
img.setAttribute("alt", "A new image description");
// Change link href
const link = document.querySelector("a");
link.setAttribute("href", "https://dailyblogs.website");
// Read an attribute value
const currentSrc = img.getAttribute("src");
console.log(currentSrc);
Creating and Removing HTML Elements
You can also create new elements from JavaScript and add them to the page — or remove existing elements completely.
Create a New Element
// Create a new paragraph element
const newPara = document.createElement("p");
// Add text to it
newPara.textContent = "This paragraph was created by JavaScript!";
// Add a class to it
newPara.classList.add("created-para");
// Append it to the body (or any container)
document.body.appendChild(newPara);
Remove an Element
const oldElement = document.getElementById("remove-me");
oldElement.remove(); // removes it from the page
JavaScript Events — Responding to the User
An event is something that happens on the page — a user clicks a button, types in a form, moves their mouse, or presses a key. JavaScript lets you listen for these events and run code when they happen.
The main way to do this is with addEventListener.
The Click Event
<button id="my-btn">Click Me</button>
<p id="result"></p>
<script>
const button = document.getElementById("my-btn");
const result = document.getElementById("result");
button.addEventListener("click", function() {
result.textContent = "You clicked the button!";
});
</script>
Every time the user clicks the button, the function runs and updates the paragraph text.
Common Event Types
Here are the most useful events you will use as a developer:
| Event Name | When It Fires |
|---|---|
click |
User clicks an element |
mouseover |
User hovers mouse over an element |
mouseout |
Mouse leaves an element |
keydown |
User presses a keyboard key |
input |
User types in an input field |
submit |
A form is submitted |
load |
Page or image finishes loading |
The Event Object
When an event fires, JavaScript automatically sends an event object to your function. This object contains useful information about what happened.
const button = document.getElementById("my-btn");
button.addEventListener("click", function(event) {
console.log(event.type); // "click"
console.log(event.target); // the button element that was clicked
});
Keyboard Events Example
<input type="text" id="name-input" placeholder="Type your name..." />
<p id="display-name"></p>
<script>
const input = document.getElementById("name-input");
const display = document.getElementById("display-name");
input.addEventListener("input", function() {
display.textContent = "Hello, " + input.value + "!";
});
</script>
Every time the user types a character, the paragraph below updates in real time.
Real Project: Interactive To-Do List
Let us put everything together and build a simple To-Do List using DOM manipulation and events. This is one of the best beginner projects to practice these skills.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>To-Do List</title>
<style>
body {
font-family: sans-serif;
max-width: 500px;
margin: 40px auto;
padding: 0 20px;
}
input {
width: 70%;
padding: 8px;
font-size: 16px;
}
button {
padding: 8px 16px;
font-size: 16px;
background: #3b82f6;
color: white;
border: none;
cursor: pointer;
border-radius: 4px;
}
li {
list-style: none;
padding: 8px 0;
border-bottom: 1px solid #e5e7eb;
display: flex;
justify-content: space-between;
}
.delete-btn {
background: #ef4444;
padding: 4px 10px;
font-size: 12px;
}
</style>
</head>
<body>
<h2>My To-Do List</h2>
<input type="text" id="task-input" placeholder="Enter a task..." />
<button id="add-btn">Add Task</button>
<ul id="task-list"></ul>
<script>
const addBtn = document.getElementById("add-btn");
const taskInput = document.getElementById("task-input");
const taskList = document.getElementById("task-list");
addBtn.addEventListener("click", function() {
const taskText = taskInput.value.trim();
if (taskText === "") {
alert("Please enter a task first!");
return;
}
// Create new list item
const li = document.createElement("li");
li.textContent = taskText;
// Create delete button
const deleteBtn = document.createElement("button");
deleteBtn.textContent = "Delete";
deleteBtn.classList.add("delete-btn");
// When delete is clicked, remove the task
deleteBtn.addEventListener("click", function() {
li.remove();
});
// Add delete button to list item
li.appendChild(deleteBtn);
// Add list item to the list
taskList.appendChild(li);
// Clear the input
taskInput.value = "";
});
</script>
</body>
</html>
This small project uses everything from Part 3:
- Selecting elements with
getElementById - Listening for a
clickevent - Reading input values
- Creating new elements with
createElement - Adding and removing elements from the DOM
- Nested event listeners inside created elements
Event Delegation — A Smart Pattern
When you have many similar elements (like many buttons or list items), adding an event listener to each one is not efficient. A smarter approach is called Event Delegation.
Instead of listening on each child element, you listen on the parent and check which child was clicked using event.target.
const taskList = document.getElementById("task-list");
taskList.addEventListener("click", function(event) {
// Check if the clicked element is a delete button
if (event.target.classList.contains("delete-btn")) {
// Remove the parent li element
event.target.parentElement.remove();
}
});
This pattern is used in real production React and Vue apps too — understanding it at the JavaScript level makes you a stronger developer.
Prevent Default Behavior
Some HTML elements have default behaviors. For example, clicking a <a> link navigates to a URL, and submitting a <form> reloads the page. You can stop this with event.preventDefault().
const form = document.querySelector("form");
form.addEventListener("submit", function(event) {
event.preventDefault(); // stops the page from reloading
const name = document.getElementById("name").value;
document.getElementById("greeting").textContent = "Hello, " + name + "!";
});
This is a very important technique — almost every form in a React or Node.js application uses preventDefault() to handle submission in JavaScript instead of the browser.
Summary — What You Learned in Part 3
Here is a quick summary of everything covered in this part of the JavaScript series:
- ✅ The DOM is a tree of your HTML that JavaScript can read and change
- ✅ Selecting elements with
getElementById,querySelector, andquerySelectorAll - ✅ Changing content with
textContentandinnerHTML - ✅ Changing styles and classes with
styleandclassList - ✅ Creating and removing elements with
createElement,appendChild, andremove() - ✅ Listening to events with
addEventListener - ✅ Common events: click, input, keydown, submit
- ✅ Event object — target, type, and more
- ✅ Event delegation for better performance
- ✅ preventDefault() to stop default browser behavior
Practice these concepts by building small projects. The To-Do List above is a great start. Try to extend it — add a feature to mark tasks as done, or save them to localStorage.
In Part 4, we will go deeper into JavaScript and cover Fetch API and AJAX — how to communicate with a backend server, get data from an API, and update the page without refreshing. This is a key skill for every MERN stack developer.
Stay tuned and keep coding! 🚀
For the official JavaScript documentation and reference, visit MDN Web Docs — JavaScript.
Tags: javascript, dom manipulation, javascript events, web development, javascript for beginners, frontend development, javascript series