JavaScript DOM Manipulation Practice Questions with Solutions

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

  1. The <h1> has an ID called heading.
  2. getElementById() finds the heading.
  3. The element is stored in the heading variable.
  4. textContent changes the text inside the heading.
  5. 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

  1. querySelectorAll() selects all elements with the message class.
  2. The result contains three paragraphs.
  3. forEach() loops through each paragraph.
  4. index tells us the position of each element.
  5. textContent changes 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

  1. JavaScript selects the container.
  2. createElement("p") creates a new paragraph.
  3. textContent adds text to the paragraph.
  4. appendChild() adds the paragraph to the container.
  5. 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

  1. The languages array contains three values.
  2. The <ul> is selected.
  3. forEach() processes each language.
  4. A new <li> is created for every language.
  5. The language name is added using textContent.
  6. 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

  1. The second paragraph has the ID removeMe.
  2. JavaScript selects it.
  3. The remove() method removes it from the DOM.
  4. 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

  1. JavaScript selects the box.
  2. JavaScript selects the button.
  3. A click event is attached to the button.
  4. When clicked, classList.add() adds the active class.
  5. The CSS rules of .active are 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

  1. JavaScript selects the message and button.
  2. A click event is added to the button.
  3. The code checks the current display value.
  4. If it is none, it changes to block.
  5. Otherwise, it changes to none.
  6. 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

  1. JavaScript selects the existing <h2>.
  2. createElement() creates a new <p>.
  3. Text is added to the paragraph.
  4. replaceWith() replaces the old heading.
  5. 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

  1. The list contains HTML and CSS.
  2. JavaScript selects the list.
  3. JavaScript selects the CSS list item.
  4. A new <li> is created.
  5. insertBefore() places the new item before CSS.
  6. 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

  1. JavaScript selects the input field.
  2. JavaScript selects the button.
  3. JavaScript selects the task list.
  4. A click event is added to the button.
  5. taskInput.value gets the user’s input.
  6. trim() removes unnecessary spaces from the beginning and end.
  7. The if statement prevents an empty task from being added.
  8. createElement("li") creates a new list item.
  9. textContent puts the task inside the list item.
  10. appendChild() adds the task to the list.
  11. 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.
  • textContent changes 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.

Scroll to Top