Paramclasses Academy - Blog

Tutorials Details

←
Post 8 of 15
→

What Is jQuery DOM Manipulation?

What Is jQuery DOM Manipulation?

October 14, 2026

What Is jQuery DOM Manipulation? Create, Insert, Update and Remove HTML Elements

Introduction to jQuery DOM Manipulation

jQuery DOM manipulation allows developers to change the structure, content and attributes of an HTML document without reloading the entire webpage.

Using jQuery, you can dynamically add new elements, update existing content, insert HTML before or after an element, and remove unwanted elements.

For example, imagine you are developing a task management application. When a user adds a new task, you can display that task immediately on the page without refreshing the browser.

jQuery makes these operations easier with methods such as:

  • append()

  • prepend()

  • before()

  • after()

  • html()

  • text()

  • empty()

  • remove()

  • replaceWith()

  • clone()

  • val()

In this tutorial, you will learn these methods with syntax, working examples and a complete practical project.

1. What Is DOM Manipulation?

DOM stands for Document Object Model. It represents an HTML document as a tree of objects that JavaScript can access and modify.

DOM manipulation means changing the HTML elements, text, attributes or structure of a webpage using JavaScript or a library such as jQuery.

Example of HTML

<div id="message">
    <h2>Welcome</h2>
    <p>This is the original message.</p>
</div>

Using jQuery, we can change the paragraph, add another element or remove the heading.

$("#message p").text("This message has been updated.");

The paragraph content changes immediately without reloading the webpage.

2. How to Use jQuery DOM Manipulation

Before using jQuery methods, include the jQuery library in your HTML document.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery DOM Manipulation</title>
</head>
<body>

    <h2 id="heading">Hello World</h2>

    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

    <script>
        $(document).ready(function () {
            $("#heading").text("Welcome to jQuery");
        });
    </script>

</body>
</html>

Output: The heading displays “Welcome to jQuery” instead of “Hello World”.

The $(document).ready() function ensures that the HTML document is ready before the jQuery code runs.

3. jQuery text() Method

The text() method gets or changes the text content of selected HTML elements.

Syntax

$(selector).text();
$(selector).text("New text");

Example

<h2 id="title">Old Title</h2>

<script>
$(document).ready(function () {
    $("#title").text("New Title");
});
</script>

Output:

New Title

You can also retrieve the current text.

let headingText = $("#title").text();
console.log(headingText);

When to use text()

Use text() when you want to display plain text, such as a success message, username, task title or notification.

4. jQuery html() Method

The html() method gets or changes the HTML content inside a selected element.

Syntax

$(selector).html();
$(selector).html("New HTML content");

Example

<div id="content">
    <p>Original content</p>
</div>

<script>
$(document).ready(function () {
    $("#content").html(
        "<h3>Updated Heading</h3><p>Updated paragraph</p>"
    );
});
</script>

Output: The original paragraph is replaced by a heading and a new paragraph.

Difference Between text() and html()

Method Purpose Example
text() Sets plain text .text("<b>Hello</b>")
html() Sets HTML markup .html("<b>Hello</b>")

Using text(), the browser displays <b>Hello</b> as text. Using html(), the browser interprets it as bold HTML markup.

Security tip: Never pass untrusted user input directly into html(). Use text() for user-provided text unless you have a proper HTML sanitization process.

5. jQuery append() Method

The append() method inserts content at the end of the selected element's existing content.

Syntax

$(selector).append("Content");

Example

<ul id="fruitList">
    <li>Apple</li>
    <li>Banana</li>
</ul>

<script>
$(document).ready(function () {
    $("#fruitList").append("<li>Mango</li>");
});
</script>

Output:

  • Apple

  • Banana

  • Mango

The new item is added after the existing list items.

Practical use

Use append() to add new tasks, products, comments, notifications or rows to a list or container.

6. jQuery prepend() Method

The prepend() method inserts content at the beginning of the selected element's content.

Example

<ul id="fruitList">
    <li>Apple</li>
    <li>Banana</li>
</ul>

<script>
$("#fruitList").prepend("<li>Mango</li>");
</script>

Output:

  • Mango

  • Apple

  • Banana

append() vs prepend()

  • append() adds content at the end.

  • prepend() adds content at the beginning.

7. jQuery before() Method

The before() method inserts content immediately before the selected element.

Example

<h2 id="title">Our Services</h2>

<script>
$("#title").before("<p>Explore what we offer</p>");
</script>

Output:

Explore what we offer
Our Services

The new paragraph is inserted outside and before the heading.

8. jQuery after() Method

The after() method inserts content immediately after the selected element.

Example

<h2 id="title">Our Services</h2>

<script>
$("#title").after("<p>Contact us to learn more.</p>");
</script>

The paragraph appears immediately after the heading.

before() vs after()

Method Insertion position
before() Before the selected element
after() After the selected element

Remember that before() and after() insert content outside the selected element, while append() and prepend() insert content inside it.

9. jQuery remove() Method

The remove() method removes the selected element and its associated jQuery data and event handlers.

Syntax

$(selector).remove();

Example

<p id="notice">This notice will be removed.</p>

<button id="removeBtn">Remove Notice</button>

<script>
$("#removeBtn").on("click", function () {
    $("#notice").remove();
});
</script>

When the user clicks the button, the paragraph disappears from the page.

Practical use

Use remove() when a user deletes a task, removes a product from a temporary list or dismisses an unwanted element.

10. jQuery empty() Method

The empty() method removes all child content from the selected element while keeping the selected element itself.

Example

<div id="box">
    <h3>Welcome</h3>
    <p>This content will be removed.</p>
</div>

<button id="clearBtn">Clear Content</button>

<script>
$("#clearBtn").on("click", function () {
    $("#box").empty();
});
</script>

After clicking the button, the div remains, but its heading and paragraph are removed.

remove() vs empty()

  • remove() deletes the selected element itself.

  • empty() keeps the selected element but removes its children.

11. jQuery replaceWith() Method

The replaceWith() method replaces the selected element with new content.

Example

<p id="oldMessage">This is the old message.</p>

<button id="replaceBtn">Replace Message</button>

<script>
$("#replaceBtn").on("click", function () {
    $("#oldMessage").replaceWith(
        "<h3 id='newMessage'>This is the new message.</h3>"
    );
});
</script>

When the button is clicked, the paragraph is replaced by a heading.

12. jQuery clone() Method

The clone() method creates a copy of the selected element.

Example

<div id="originalBox">
    <p>Hello, jQuery!</p>
</div>

<div id="copyArea"></div>

<script>
$(document).ready(function () {
    let copiedContent = $("#originalBox").clone();
    $("#copyArea").append(copiedContent);
});
</script>

Output: The paragraph appears in both the original box and the copy area.

By default, clone() does not copy jQuery event handlers or data. You can use clone(true) when copying those is intentional, but be careful when cloning elements with IDs because duplicate IDs can cause problems.

13. jQuery val() Method

The val() method gets or sets the value of form elements such as input fields, textareas and select boxes.

Syntax

$(selector).val();
$(selector).val("New value");

Example

<input type="text" id="username" value="Guest">

<button id="updateBtn">Update Name</button>

<script>
$("#updateBtn").on("click", function () {
    $("#username").val("Student");
});
</script>

When the button is clicked, the input value changes from “Guest” to “Student”.

Getting an input value

let username = $("#username").val();
console.log(username);

Use .val() to read form input before submitting data or to update a field during an interaction.

14. Complete Practical Project: Dynamic Task List

Let's build a simple task list that allows users to add, complete and delete tasks without refreshing the page.

Complete HTML, CSS and jQuery Code

Copy the following code into a file named jquery-dom-manipulation.html and open it in your browser. An internet connection is required to load jQuery from the CDN.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>jQuery DOM Manipulation Project</title>

    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

    <style>
        * {
            box-sizing: border-box;
        }

        body {
            margin: 0;
            padding: 30px 15px;
            font-family: Arial, sans-serif;
            background: #f1f5f9;
        }

        .container {
            max-width: 650px;
            margin: auto;
            padding: 25px;
            background: #ffffff;
            border-radius: 12px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
        }

        h1 {
            margin-top: 0;
            color: #1d4ed8;
            text-align: center;
        }

        .input-group {
            display: flex;
            gap: 10px;
        }

        #taskInput {
            flex: 1;
            min-width: 0;
            padding: 12px;
            border: 1px solid #cbd5e1;
            border-radius: 6px;
            font-size: 16px;
        }

        button {
            padding: 10px 14px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
        }

        #addBtn {
            background: #2563eb;
            color: #ffffff;
        }

        #taskList {
            list-style: none;
            padding: 0;
            margin-top: 20px;
        }

        .task-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 12px;
            margin-bottom: 10px;
            padding: 12px;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            overflow-wrap: anywhere;
        }

        .task-text {
            flex: 1;
        }

        .completed .task-text {
            text-decoration: line-through;
            color: #64748b;
        }

        .task-actions {
            display: flex;
            gap: 6px;
            flex-wrap: wrap;
        }

        .complete-btn {
            background: #16a34a;
            color: white;
        }

        .delete-btn {
            background: #dc2626;
            color: white;
        }

        #message {
            margin-top: 12px;
            color: #b91c1c;
        }

        @media (max-width: 480px) {
            .container {
                padding: 18px;
            }

            .input-group {
                flex-direction: column;
            }

            #addBtn {
                width: 100%;
            }

            .task-item {
                align-items: flex-start;
                flex-direction: column;
            }
        }
    </style>
</head>

<body>

<div class="container">

    <h1>My Task List</h1>

    <div class="input-group">
        <input
            type="text"
            id="taskInput"
            placeholder="Enter your task"
            aria-label="Enter a task"
        >

        <button type="button" id="addBtn">Add Task</button>
    </div>

    <p id="message" role="status" aria-live="polite"></p>

    <ul id="taskList"></ul>

</div>

<script>
$(document).ready(function () {

    // Add a new task
    $("#addBtn").on("click", function () {

        let task = $("#taskInput").val().trim();

        if (task === "") {
            $("#message").text("Please enter a task.");
            return;
        }

        // Build elements safely using text()
        let taskText = $("<span>")
            .addClass("task-text")
            .text(task);

        let completeButton = $("<button>")
            .attr("type", "button")
            .addClass("complete-btn")
            .text("Complete");

        let deleteButton = $("<button>")
            .attr("type", "button")
            .addClass("delete-btn")
            .text("Delete");

        let actions = $("<div>")
            .addClass("task-actions")
            .append(completeButton, deleteButton);

        let taskItem = $("<li>")
            .addClass("task-item")
            .append(taskText, actions);

        $("#taskList").append(taskItem);

        $("#taskInput").val("");
        $("#message").text("");
        $("#taskInput").trigger("focus");
    });

    // Mark a task as completed
    $("#taskList").on("click", ".complete-btn", function () {

        let taskItem = $(this).closest(".task-item");

        taskItem.toggleClass("completed");

        if (taskItem.hasClass("completed")) {
            $(this).text("Undo");
        } else {
            $(this).text("Complete");
        }
    });

    // Delete a task
    $("#taskList").on("click", ".delete-btn", function () {
        $(this).closest(".task-item").remove();
    });

    // Add a task when Enter is pressed
    $("#taskInput").on("keydown", function (event) {

        if (event.key === "Enter") {
            $("#addBtn").trigger("click");
        }
    });

});
</script>

</body>
</html>

Features of this project

  1. Users can add new tasks.

  2. Empty tasks are rejected.

  3. Tasks can be marked as completed.

  4. Completed tasks can be marked as pending again.

  5. Users can delete tasks.

  6. The Enter key adds a task.

  7. The layout adjusts for mobile screens.

  8. User-entered text is inserted safely using .text() rather than being interpreted as HTML.

Important: This is a front-end demonstration. Tasks are not saved permanently; they disappear when the page is reloaded. Saving tasks requires a database or browser storage.

15. Explanation of Important Code

Creating an element

let taskItem = $("<li>");

This creates a new li element in memory.

Adding a CSS class

taskItem.addClass("task-item");

This assigns the CSS class used to style the task.

Adding content

taskItem.append(taskText, actions);

This inserts the task text and action buttons inside the list item.

Adding the task to the page

$("#taskList").append(taskItem);

This places the new task at the end of the task list.

Finding the current task

$(this).closest(".task-item");

This finds the nearest ancestor with the task-item class relative to the clicked button.

Removing the task

$(this).closest(".task-item").remove();

This removes only the task containing the clicked Delete button.

Handling dynamically created buttons

$("#taskList").on("click", ".delete-btn", function () {
    $(this).closest(".task-item").remove();
});

This uses delegated event handling. Because task buttons are created dynamically, attaching the event to the existing #taskList allows it to handle clicks on new buttons too.

16. Common Mistakes in jQuery DOM Manipulation

Mistake 1: Forgetting the jQuery library

If jQuery is not loaded, you may see an error such as jQuery is not defined or $ is not defined.

Solution: Check the CDN URL and ensure the library loads before your script executes.

Mistake 2: Using the wrong selector

$("#task").remove();

This selects an element with the ID task, not an element with the class task.

Use .task to select a class:

$(".task").remove();

Mistake 3: Confusing append() and after()

append() inserts content inside an element, while after() inserts it after the element.

Choose the method according to the desired HTML structure.

Mistake 4: Using html() with untrusted input

$("#result").html(userInput);

This can introduce cross-site scripting (XSS) if userInput contains malicious HTML or script-capable markup.

For plain user text, prefer:

$("#result").text(userInput);

Mistake 5: Using duplicate IDs

Every ID should be unique within a document. Use classes for repeated task items and their buttons.

Mistake 6: Attaching events only to existing dynamic elements

If a button is created after an event handler is attached, a directly bound handler may not work for that new button.

Use delegated event handling when appropriate:

$("#taskList").on("click", ".delete-btn", function () {
    $(this).closest(".task-item").remove();
});

17. Best Practices for jQuery DOM Manipulation

  • Use clear and descriptive selectors.

  • Use text() for plain user-provided text.

  • Avoid inserting unsanitized user input through html().

  • Use delegated events for dynamically created elements.

  • Prefer reusable functions when the same DOM operation is needed repeatedly.

  • Avoid unnecessary DOM updates inside large loops.

  • Use unique IDs and reusable CSS classes.

  • Keep HTML, CSS and JavaScript organized for maintainability.

  • Test all interactions on desktop and mobile screens.

  • Remember that DOM changes alone do not save data to a database.

18. Frequently Asked Questions (FAQs)

Q1. What is jQuery DOM manipulation?

jQuery DOM manipulation is the process of dynamically changing HTML elements, their content, or their position using jQuery methods.

Q2. Which jQuery method adds content at the end of an element?

The append() method adds content at the end of the selected element's existing content.

Q3. What is the difference between append() and prepend()?

append() adds content at the end, whereas prepend() adds content at the beginning.

Q4. What is the difference between html() and text()?

html() works with HTML markup, while text() works with plain text content.

Q5. What is the difference between remove() and empty()?

remove() removes the selected element itself. empty() removes its child content but keeps the selected element.

Q6. Can jQuery create new HTML elements?

Yes. For example:

let newElement = $("<p>").text("New paragraph");
$("body").append(newElement);

Q7. Does DOM manipulation save data permanently?

No. Changing the DOM updates the current page only. Permanent storage requires a database or another storage mechanism.

Q8. Can jQuery DOM manipulation be used in AJAX applications?

Yes. You can use jQuery DOM methods to display data returned by an AJAX request without reloading the entire page.

19. jQuery DOM Manipulation Interview Questions

  1. What is DOM manipulation?

  2. What is the difference between append() and prepend()?

  3. Explain the difference between before() and after().

  4. What is the difference between html() and text()?

  5. How do you create a new HTML element using jQuery?

  6. What is the difference between remove() and empty()?

  7. What does the replaceWith() method do?

  8. How does the clone() method work?

  9. What is delegated event handling?

  10. How can you safely display user-entered text using jQuery?

20. Practice Exercises

Try these exercises yourself:

Exercise 1: Create a button that changes the text of an existing paragraph.

Exercise 2: Create an input field and a button that adds the entered value to a list using append().

Exercise 3: Create two buttons: one that clears the contents of a div and another that removes the entire div.

Exercise 4: Create a list with three items and use prepend() to add a fourth item at the beginning.

Exercise 5: Create a simple product list where users can add and remove products dynamically.

21. Multiple-Choice Questions (MCQs)

Q1. Which jQuery method adds content at the end of an element?

A. prepend()

B. append()

C. before()

D. remove()

Correct Answer: B. append()

Q2. Which method changes an element's plain text?

A. text()

B. clone()

C. remove()

D. after()

Correct Answer: A. text()

Q3. Which method removes all child elements while keeping the selected element?

A. remove()

B. replaceWith()

C. empty()

D. before()

Correct Answer: C. empty()

Q4. Which method inserts content before the selected element?

A. after()

B. append()

C. prepend()

D. before()

Correct Answer: D. before()

Q5. Which jQuery method gets or sets a form input's value?

A. val()

B. html()

C. clone()

D. empty()

Correct Answer: A. val()

Conclusion

jQuery DOM manipulation is an important part of building interactive webpages. It enables developers to create new HTML elements, update text, insert content, remove unwanted elements and work with form values.

Methods such as append(), prepend(), text(), html(), remove(), empty() and val() help make these tasks straightforward.

By completing the dynamic task list project, you have practiced creating elements, inserting them into the DOM, handling events and removing elements without refreshing the page.

←
Post 8 of 15
→