Introductions
DOM manipulation means using JavaScript to change, create, remove, or update HTML elements on a webpage. It is one of the most important skills for building interactive websites. In this chapter, you will practice selecting elements, changing content, creating elements, adding and removing elements, modifying classes, and working with user interactions. JavaScript DOM manipulation Practice questions with solutions help to understand the concpets.
Question 1: Change the Text of an HTML Element
Problem
Create a heading and use JavaScript to change its text.
Solution
<h1 id="heading">Welcome</h1>
<script>
const heading = document.getElementById("heading");
heading.textContent = "Welcome to JavaScript";
</script>
Output
Welcome to JavaScript
Step-by-step Explanation
- The
<h1>has an ID calledheading. getElementById()finds the heading.- The element is stored in the
headingvariable. textContentchanges the text inside the heading.- The browser displays the new text.
Question 2: Change the Content of Multiple Elements
Problem
Create three paragraphs with the same class and change their text using JavaScript.
Solution
<p class="message">Message 1</p>
<p class="message">Message 2</p>
<p class="message">Message 3</p>
<script>
const messages = document.querySelectorAll(".message");
messages.forEach(function(message, index) {
message.textContent = "Updated Message " + (index + 1);
});
</script>
Output
Updated Message 1
Updated Message 2
Updated Message 3
Step-by-step Explanation
querySelectorAll()selects all elements with themessageclass.- The result contains three paragraphs.
forEach()loops through each paragraph.indextells us the position of each element.textContentchanges each paragraph’s text.
Question 3: Create a New HTML Element
Problem
Create a new paragraph using JavaScript and add it to the webpage.
Solution
<div id="container"></div>
<script>
const container = document.getElementById("container");
const paragraph = document.createElement("p");
paragraph.textContent = "This paragraph was created using JavaScript.";
container.appendChild(paragraph);
</script>
Output
This paragraph was created using JavaScript.
Step-by-step Explanation
- JavaScript selects the container.
createElement("p")creates a new paragraph.textContentadds text to the paragraph.appendChild()adds the paragraph to the container.- The new paragraph becomes part of the DOM.
Question 4: Add Multiple List Items Dynamically
Problem
Create an empty <ul> and use JavaScript to add three programming languages to it.
Solution
<ul id="languages"></ul>
<script>
const languages = ["JavaScript", "Python", "Java"];
const list = document.getElementById("languages");
languages.forEach(function(language) {
const item = document.createElement("li");
item.textContent = language;
list.appendChild(item);
});
</script>
Output
JavaScript
Python
Java
Step-by-step Explanation
- The
languagesarray contains three values. - The
<ul>is selected. forEach()processes each language.- A new
<li>is created for every language. - The language name is added using
textContent. appendChild()adds each<li>to the list.
Question 5: Remove an HTML Element
Problem
Create three paragraphs and remove the second paragraph using JavaScript.
Solution
<p>First Paragraph</p>
<p id="removeMe">Second Paragraph</p>
<p>Third Paragraph</p>
<script>
const paragraph = document.getElementById("removeMe");
paragraph.remove();
</script>
Output
First Paragraph
Third Paragraph
Step-by-step Explanation
- The second paragraph has the ID
removeMe. - JavaScript selects it.
- The
remove()method removes it from the DOM. - Only the first and third paragraphs remain.
Question 6: Add and Remove CSS Classes
Problem
Create a box and a button. When the button is clicked, add a CSS class to the box.
Solution
<style>
.active {
background-color: green;
color: white;
padding: 20px;
}
</style>
<div id="box">My Box</div>
<button id="button">Activate</button>
<script>
const box = document.getElementById("box");
const button = document.getElementById("button");
button.addEventListener("click", function() {
box.classList.add("active");
});
</script>
Output
Before clicking:
My Box
[Activate]
After clicking:
The box receives the active styling.
Step-by-step Explanation
- JavaScript selects the box.
- JavaScript selects the button.
- A click event is attached to the button.
- When clicked,
classList.add()adds theactiveclass. - The CSS rules of
.activeare applied.
Question 7: Toggle an Element’s Visibility
Problem
Create a paragraph and a button. When the button is clicked, show or hide the paragraph.
Solution
<p id="message">This message can be hidden.</p>
<button id="toggleButton">Show / Hide</button>
<script>
const message = document.getElementById("message");
const button = document.getElementById("toggleButton");
button.addEventListener("click", function() {
if (message.style.display === "none") {
message.style.display = "block";
} else {
message.style.display = "none";
}
});
</script>
Output
Before clicking:
This message can be hidden.
[Show / Hide]
After clicking:
[Show / Hide]
Clicking again displays the message.
Step-by-step Explanation
- JavaScript selects the message and button.
- A click event is added to the button.
- The code checks the current
displayvalue. - If it is
none, it changes toblock. - Otherwise, it changes to
none. - This creates a simple show/hide feature.
Question 8: Replace an Existing Element
Problem
Create a heading and replace it with a new paragraph using JavaScript.
Solution
<div id="container">
<h2 id="oldHeading">Old Heading</h2>
</div>
<script>
const oldHeading = document.getElementById("oldHeading");
const newParagraph = document.createElement("p");
newParagraph.textContent = "The heading was replaced.";
oldHeading.replaceWith(newParagraph);
</script>
Output
The heading was replaced.
Step-by-step Explanation
- JavaScript selects the existing
<h2>. createElement()creates a new<p>.- Text is added to the paragraph.
replaceWith()replaces the old heading.- The new paragraph appears in its place.
Question 9: Insert an Element Before Another Element
Problem
Create a list containing two items. Use JavaScript to add a new item before the second item.
Solution
<ul id="list">
<li>HTML</li>
<li id="css">CSS</li>
</ul>
<script>
const list = document.getElementById("list");
const css = document.getElementById("css");
const javascript = document.createElement("li");
javascript.textContent = "JavaScript";
list.insertBefore(javascript, css);
</script>
Output
HTML
JavaScript
CSS
Step-by-step Explanation
- The list contains HTML and CSS.
- JavaScript selects the list.
- JavaScript selects the CSS list item.
- A new
<li>is created. insertBefore()places the new item before CSS.- The final order becomes HTML, JavaScript, CSS.
Question 10: Build a Simple Dynamic To-Do List
Problem
Create an input field and button. When the user enters a task and clicks the button, add the task to a list.
Solution
<input id="taskInput" type="text" placeholder="Enter a task">
<button id="addButton">Add Task</button>
<ul id="taskList"></ul>
<script>
const taskInput = document.getElementById("taskInput");
const addButton = document.getElementById("addButton");
const taskList = document.getElementById("taskList");
addButton.addEventListener("click", function() {
const taskText = taskInput.value.trim();
if (taskText === "") {
return;
}
const task = document.createElement("li");
task.textContent = taskText;
taskList.appendChild(task);
taskInput.value = "";
});
</script>
Output
If the user enters:
Learn JavaScript
and clicks Add Task, the list becomes:
Learn JavaScript
If the user enters:
Practice DOM
the list becomes:
Learn JavaScript
Practice DOM
Step-by-step Explanation
- JavaScript selects the input field.
- JavaScript selects the button.
- JavaScript selects the task list.
- A click event is added to the button.
taskInput.valuegets the user’s input.trim()removes unnecessary spaces from the beginning and end.- The
ifstatement prevents an empty task from being added. createElement("li")creates a new list item.textContentputs the task inside the list item.appendChild()adds the task to the list.taskInput.value = ""clears the input field.
Key Takeaways
- DOM manipulation allows JavaScript to dynamically change webpages.
getElementById()selects an element using its ID.querySelectorAll()selects multiple elements.textContentchanges an element’s text.createElement()creates new HTML elements.appendChild()adds an element to another element.remove()removes an element from the DOM.replaceWith()replaces an existing element.insertBefore()inserts an element before another element.classList.add()adds a CSS class.classList.remove()removes a CSS class.classList.toggle()can add or remove a class.addEventListener()makes DOM manipulation interactive.- DOM manipulation is the foundation of dynamic and interactive websites.
FAQs
1. What is DOM manipulation in JavaScript?
DOM manipulation means using JavaScript to access and change HTML elements on a webpage.
For example:
document.getElementById("heading").textContent = "Hello";
This changes the text of an HTML element.
2. How do I create an HTML element using JavaScript?
Use document.createElement().
const paragraph = document.createElement("p");
paragraph.textContent = "Hello JavaScript";
3. How do I add a newly created element to a webpage?
Use appendChild().
const paragraph = document.createElement("p");
paragraph.textContent = "Hello";
document.body.appendChild(paragraph);
4. How do I remove an element from the DOM?
You can use the remove() method.
const element = document.getElementById("message");
element.remove();
5. What is classList used for?
classList is used to add, remove, toggle, and check CSS classes.
element.classList.add("active");
element.classList.remove("active");
element.classList.toggle("active");
6. What is appendChild()?
appendChild() adds a node as the last child of another element.
const list = document.getElementById("list");
const item = document.createElement("li");
item.textContent = "JavaScript";
list.appendChild(item);
7. Why is DOM manipulation important?
DOM manipulation allows JavaScript to create interactive webpages such as:
- To-do lists
- Dynamic menus
- Form validation
- Image galleries
- Popups
- Tabs
- Counters
- Interactive dashboards
- Shopping carts
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
