Paramclasses Academy - Blog

Tutorials Details

←
Post 5 of 15
→

What Is jQuery HTML Manipulation?

What Is jQuery HTML Manipulation?

October 14, 2026

What Is jQuery HTML Manipulation? Get, Set, Add and Remove HTML Elements

Introduction to jQuery HTML Manipulation

Websites often need to update their content without reloading the entire page. For example, an online shopping website may add a new product to a cart, a task management application may add a task to a list, or a contact form may display a message after submission.

jQuery HTML manipulation makes these operations easier by allowing developers to read, update, insert and remove HTML content using simple methods.

In this tutorial, you will learn how to get and set HTML content, change text, work with input values, add new elements, remove existing elements and build a practical project using jQuery.

What Is jQuery HTML Manipulation?

jQuery HTML manipulation is the process of accessing and changing the content or structure of HTML elements using jQuery methods.

It allows you to perform tasks such as:

  • Reading the text of an element.

  • Updating HTML content.

  • Getting or setting input field values.

  • Adding new elements inside another element.

  • Inserting elements before or after existing elements.

  • Removing HTML elements.

  • Clearing the content of an element.

These operations are commonly used in dynamic websites, form handling, shopping carts, task lists and interactive dashboards.

1. jQuery html() Method

The html() method is used to get or set the HTML content inside a selected element.

When used without an argument, it returns the HTML content of the first selected element. When a value is provided, it replaces the existing content with the supplied HTML.

Syntax

Get HTML content:

$(selector).html();

Set HTML content:

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

Example: Get HTML Content

<div id="content">
    <h3>Welcome</h3>
    <p>Learn jQuery step by step.</p>
</div>

<button id="getHtml">Get HTML</button>

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

<script>
$(document).ready(function () {
    $("#getHtml").on("click", function () {
        let content = $("#content").html();

        console.log(content);
    });
});
</script>

Expected Output

When you click the button, the browser console displays the HTML inside the content element, including the heading and paragraph tags.

<h3>Welcome</h3>
<p>Learn jQuery step by step.</p>

Explanation

  1. $("#content") selects the element with the ID content.

  2. .html() retrieves its inner HTML.

  3. The returned content is stored in the content variable.

  4. console.log() displays the result in the browser console.

Example: Set HTML Content

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

<button id="updateHtml">Update Content</button>

<script>
$(document).ready(function () {
    $("#updateHtml").on("click", function () {
        $("#message").html(
            "<h3>Welcome!</h3><p>Content updated successfully.</p>"
        );
    });
});
</script>

Expected Output

Initially, the page displays Original content.

After clicking the button, the element displays a heading and paragraph with the updated content.

Important Note

The html() method interprets the supplied string as HTML. Never insert untrusted user input directly through html(), because unsafe HTML can create cross-site scripting (XSS) vulnerabilities. Use text() when you want to display user-provided content as plain text.

2. jQuery text() Method

The text() method is used to get or set the text content of an element.

Unlike html(), the text() method does not interpret supplied strings as HTML markup.

Syntax

Get text:

$(selector).text();

Set text:

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

Example: Get Text

<p id="description">
    jQuery makes JavaScript easier to use.
</p>

<button id="getText">Get Text</button>

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

<script>
$(document).ready(function () {
    $("#getText").on("click", function () {
        let result = $("#description").text();

        console.log(result);
    });
});
</script>

Expected Output

The browser console displays:

jQuery makes JavaScript easier to use.

Example: Set Text

<p id="result">Old message</p>

<button id="changeText">Change Text</button>

<script>
$(document).ready(function () {
    $("#changeText").on("click", function () {
        $("#result").text("Welcome to our website!");
    });
});
</script>

Expected Output

Clicking the button changes the paragraph to:

Welcome to our website!

Difference Between html() and text()

Method Purpose How HTML markup is handled
html() Gets or sets HTML content. Supplied HTML strings are interpreted as markup.
text() Gets or sets text content. Supplied strings are displayed as text.

For example:

$("#result").html("<strong>Hello</strong>");

This displays Hello in bold.

$("#result").text("<strong>Hello</strong>");

This displays the literal text <strong>Hello</strong>.

3. jQuery val() Method

The val() method is used to get or set the value of form controls, such as text inputs, password fields, dropdown lists and textareas.

Syntax

Get a value:

$(selector).val();

Set a value:

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

Example: Get an Input Value

<input type="text" id="username" placeholder="Enter your name">

<button id="getValue">Get Value</button>

<p id="output"></p>

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

<script>
$(document).ready(function () {
    $("#getValue").on("click", function () {
        let name = $("#username").val();

        $("#output").text("Your name is: " + name);
    });
});
</script>

Expected Output

If the user enters Rahul and clicks the button, the page displays:

Your name is: Rahul

Explanation

  • $("#username") selects the input field.

  • .val() retrieves the entered value.

  • The value is stored in the name variable.

  • .text() displays the result in the paragraph.

Example: Set an Input Value

<input type="text" id="email" placeholder="Enter your email">

<button id="setEmail">Set Email</button>

<script>
$(document).ready(function () {
    $("#setEmail").on("click", function () {
        $("#email").val("student@example.com");
    });
});
</script>

Expected Output: Clicking the button fills the input field with student@example.com.

Practical Uses of val()

  • Reading login form values.

  • Filling edit forms with existing data.

  • Getting selected dropdown options.

  • Clearing form fields after successful submission.

  • Collecting data before sending an AJAX request.

4. jQuery append() Method

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

It is useful for adding list items, notifications, products and tasks dynamically.

Syntax

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

Example: Add a List Item

<ul id="studentList">
    <li>Rahul</li>
    <li>Amit</li>
</ul>

<button id="addStudent">Add Student</button>

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

<script>
$(document).ready(function () {
    $("#addStudent").on("click", function () {
        $("#studentList").append("<li>Priya</li>");
    });
});
</script>

Expected Output

Initially, the list contains:

  • Rahul

  • Amit

After clicking Add Student, it contains:

  • Rahul

  • Amit

  • Priya

Each click adds another Priya list item.

Explanation

  1. $("#studentList") selects the unordered list.

  2. .append() inserts new content at the end of that list.

  3. The new <li> becomes a child of the <ul>.

Practical Uses

  • Adding tasks to a To-Do list.

  • Adding products to a cart display.

  • Appending comments to a discussion.

  • Displaying additional rows in a list.

5. jQuery prepend() Method

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

Syntax

$(selector).prepend("New Content");

Example: Add an Item at the Beginning

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

<button id="addFruit">Add Fruit First</button>

<script>
$(document).ready(function () {
    $("#addFruit").on("click", function () {
        $("#fruitList").prepend("<li>Apple</li>");
    });
});
</script>

Expected Output

Before clicking the button:

  • Banana

  • Mango

After clicking the button:

  • Apple

  • Banana

  • Mango

Explanation

The prepend() method inserts the new list item before the existing child items, making it the first item in the list.

Difference Between append() and prepend()

Method Where Content Is Added
append() At the end of the selected element's content.
prepend() At the beginning of the selected element's content.

6. jQuery before() Method

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

The inserted content becomes a sibling of the selected element rather than a child inside it.

Syntax

$(selector).before("New Content");

Example

<p id="target">This is the original paragraph.</p>

<button id="addBefore">Add Before</button>

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

<script>
$(document).ready(function () {
    $("#addBefore").on("click", function () {
        $("#target").before("<p>This paragraph was added before.</p>");
    });
});
</script>

Expected Output

After clicking the button, the new paragraph appears above the original paragraph.

Explanation

before() inserts the new paragraph immediately before the element with ID target.

7. jQuery after() Method

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

The new content becomes a sibling of the selected element.

Syntax

$(selector).after("New Content");

Example

<p id="target">This is the original paragraph.</p>

<button id="addAfter">Add After</button>

<script>
$(document).ready(function () {
    $("#addAfter").on("click", function () {
        $("#target").after("<p>This paragraph was added after.</p>");
    });
});
</script>

Expected Output

After clicking the button, the new paragraph appears below the original paragraph.

Difference Between before() and after()

Method Position
before() Inserts content immediately before the selected element.
after() Inserts content immediately after the selected element.

Difference Between append() and after()

Consider this HTML:

<div id="container">
    <p>Original paragraph</p>
</div>

Using:

$("#container").append("<p>New paragraph</p>");

The new paragraph is inserted inside the div, after its existing child content.

Using:

$("#container").after("<p>New paragraph</p>");

The new paragraph is inserted outside the div, immediately after it.

This distinction is important when building dynamic page layouts.

8. jQuery remove() Method

The remove() method removes the selected HTML element, including its child elements and associated jQuery data and event handlers.

Syntax

$(selector).remove();

Example: Remove a List Item

<ul id="taskList">
    <li>Learn HTML</li>
    <li id="removeTask">Learn jQuery</li>
    <li>Learn CSS</li>
</ul>

<button id="deleteTask">Delete Task</button>

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

<script>
$(document).ready(function () {
    $("#deleteTask").on("click", function () {
        $("#removeTask").remove();
    });
});
</script>

Expected Output

Before clicking the button, the list contains three items.

After clicking Delete Task, the Learn jQuery item is removed from the page.

Practical Uses

  • Removing completed tasks.

  • Deleting a product from a displayed list.

  • Removing a notification.

  • Deleting a row from a temporary interface.

Important: Removing an element from the page does not automatically delete the corresponding record from a database. Database deletion requires a request to the server and appropriate backend logic.

9. jQuery empty() Method

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

Syntax

$(selector).empty();

Example

<div id="contentBox">
    <h3>Welcome</h3>
    <p>This is some content.</p>
    <button>Inner Button</button>
</div>

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

<script>
$(document).ready(function () {
    $("#clearContent").on("click", function () {
        $("#contentBox").empty();
    });
});
</script>

Expected Output

After clicking Clear Content, the heading, paragraph and inner button disappear. The contentBox div remains on the page, but its contents are removed.

Difference Between remove() and empty()

Method What It Removes
remove() Removes the selected element and its contents.
empty() Removes the selected element's contents but keeps the element itself.

10. jQuery replaceWith() Method

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

Syntax

$(selector).replaceWith("New Content");

Example

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

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

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

<script>
$(document).ready(function () {
    $("#replaceButton").on("click", function () {
        $("#oldMessage").replaceWith(
            "<h3>New message displayed!</h3>"
        );
    });
});
</script>

Expected Output

After clicking the button, the original paragraph is replaced by a heading.

Explanation

  • $("#oldMessage") selects the original paragraph.

  • replaceWith() replaces that paragraph with the supplied HTML.

  • The replacement becomes a new element in the document.

11. jQuery clone() Method

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

It is useful when you need to duplicate cards, form sections or list items.

Syntax

$(selector).clone();

Example: Clone a Product Card

<div id="productCard">
    <h3>Wireless Mouse</h3>
    <p>Price: ₹599</p>
</div>

<button id="cloneProduct">Duplicate Product</button>

<div id="productList"></div>

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

<script>
$(document).ready(function () {
    $("#cloneProduct").on("click", function () {
        let copy = $("#productCard").clone();

        $("#productList").append(copy);
    });
});
</script>

Expected Output

Clicking Duplicate Product adds a copy of the product card to the productList container.

Important Note

The example clones the product card each time the button is clicked. In a real application, use unique IDs or classes appropriately so that duplicated elements do not create duplicate HTML IDs.

By default, clone() does not copy jQuery event handlers and data. The optional clone(true) form can copy them, but it should be used carefully.

12. Complete Practical Example: jQuery Dynamic Task List

Now, combine several HTML manipulation methods to create a small task list.

This example allows users to add tasks, remove individual tasks and clear the list.

Complete HTML, CSS and jQuery Code

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

    <title>jQuery Dynamic Task List</title>

    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 600px;
            margin: 40px auto;
            padding: 20px;
            background: #f4f7fb;
        }

        h1 {
            color: #173b72;
        }

        input {
            padding: 10px;
            width: 65%;
            max-width: 320px;
        }

        button {
            padding: 10px 14px;
            margin: 5px;
            border: none;
            border-radius: 5px;
            background: #1769aa;
            color: white;
            cursor: pointer;
        }

        ul {
            padding-left: 20px;
        }

        li {
            margin: 12px 0;
        }

        .deleteTask {
            background: #d93025;
        }
    </style>
</head>
<body>

    <h1>My Task List</h1>

    <input type="text" id="taskInput" placeholder="Enter a task">

    <button id="addTask">Add Task</button>
    <button id="clearTasks">Clear All</button>

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

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

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

            // Add a new task
            $("#addTask").on("click", function () {
                let task = $("#taskInput").val().trim();

                if (task === "") {
                    alert("Please enter a task.");
                    return;
                }

                let listItem = $("<li></li>").text(task);
                let deleteButton = $("<button></button>")
                    .text("Delete")
                    .addClass("deleteTask");

                listItem.append(" ", deleteButton);
                $("#taskList").append(listItem);

                $("#taskInput").val("");
            });

            // Delete one task using event delegation
            $("#taskList").on("click", ".deleteTask", function () {
                $(this).parent().remove();
            });

            // Remove all tasks but keep the list
            $("#clearTasks").on("click", function () {
                $("#taskList").empty();
            });

        });
    </script>

</body>
</html>

How to Run the Project

  1. Open Visual Studio Code.

  2. Create a file named jquery-html-manipulation.html.

  3. Copy and paste the complete code.

  4. Save the file.

  5. Open it in a browser, or use Live Server.

  6. Enter a task and click Add Task.

  7. Click Delete to remove an individual task.

  8. Click Clear All to remove every task from the list.

How This Project Works

Adding a task

The code reads the input value with val(), removes surrounding whitespace with trim(), and creates a new list item.

The task is added using append().

Deleting a task

The delegated click handler listens for clicks on buttons with the deleteTask class. The expression $(this).parent().remove() removes the list item containing the clicked button.

Clearing the list

The empty() method removes all list items while keeping the ul element in the document.

Creating safe text content

The task is inserted with .text(task) rather than interpreting the user's input as HTML. This is a safer approach for displaying user-provided text.

Common Mistakes in jQuery HTML Manipulation

1. Confusing html() and text()

The html() method interprets HTML markup, while text() treats supplied strings as text.

Solution: Use text() for plain text, especially when displaying user input.

2. Using text() Instead of val() for an Input

$("#username").text();

This does not retrieve the current value of a text input.

Correct approach:

$("#username").val();

3. Confusing append() and after()

append() adds content inside the selected element, while after() inserts content outside it, immediately afterward.

Solution: Check whether the new element should be a child or a sibling.

4. Removing the Wrong Element

$(this).remove();

This removes the element that triggered the event. If the event was triggered by a Delete button, it removes the button rather than the whole task row.

Solution: If the button is inside a list item, use the appropriate parent or closest matching container:

$(this).closest("li").remove();

5. Using Duplicate IDs

If cloned or dynamically generated HTML contains repeated IDs, selectors may target the wrong element.

Solution: Use unique IDs or classes for repeated elements.

6. Inserting Untrusted Content as HTML

Using html() or HTML strings to insert untrusted input may introduce security vulnerabilities.

Solution: Create elements with jQuery and insert user input through .text().

Best Practices for jQuery HTML Manipulation

  • Use text() for displaying plain text.

  • Use val() to read or set form control values.

  • Use html() only when inserting trusted HTML markup.

  • Choose append(), prepend(), before() or after() according to the required position.

  • Use remove() when deleting an element and empty() when clearing its contents.

  • Use event delegation for interactive elements created dynamically.

  • Avoid duplicate HTML IDs.

  • Validate and sanitize data appropriately on the server when working with user submissions.

  • Keep your jQuery code readable and organized.

Frequently Asked Questions (FAQs)

1. What is jQuery HTML manipulation?

jQuery HTML manipulation is the process of reading, updating, adding or removing HTML content using jQuery methods.

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

html() gets or sets HTML content, whereas text() gets or sets plain text content.

3. What is the use of the val() method?

The val() method reads or sets the value of form controls, such as input fields, dropdowns and textareas.

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

append() inserts content at the end of an element's content, while prepend() inserts it at the beginning.

5. What is the difference between before() and after()?

before() inserts content immediately before the selected element, while after() inserts content immediately after it.

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

remove() deletes the selected element and its contents. empty() removes the element's contents but leaves the selected element itself.

7. What is the use of replaceWith()?

replaceWith() replaces a selected element with new content.

8. What is the use of clone()?

clone() creates a copy of a selected element.

9. Can jQuery add HTML elements dynamically?

Yes. Methods such as append(), prepend(), before() and after() can insert new elements dynamically.

10. Does removing an HTML element delete its database record?

No. Removing an element only changes the webpage. Deleting a database record requires backend processing and a server request.

jQuery HTML Manipulation Interview Questions

  1. What is HTML manipulation in jQuery?

  2. Explain the html() and text() methods with examples.

  3. What is the purpose of the val() method?

  4. Explain the difference between append() and prepend().

  5. What is the difference between before() and after()?

  6. Explain remove() and empty().

  7. What does replaceWith() do?

  8. What is the purpose of the clone() method?

  9. How can you add an HTML element dynamically using jQuery?

  10. Why should user input generally be inserted using text() instead of html()?

Practice Exercises

Try these exercises to strengthen your understanding of jQuery HTML manipulation.

  1. Create a button that changes a paragraph's content using text().

  2. Create another button that inserts a heading using html().

  3. Create an input field and display its value after clicking a button.

  4. Add a new list item using append().

  5. Add a new list item at the beginning using prepend().

  6. Insert a paragraph before another paragraph using before().

  7. Insert a paragraph after another paragraph using after().

  8. Create a Delete button that removes a specific list item.

  9. Create a Clear All button that empties a list.

  10. Build a product card and duplicate it using clone().

Multiple-Choice Questions (MCQs)

1. Which method is used to get or set HTML content?

A. val()

B. html()

C. remove()

D. empty()

Correct Answer: B. html()

2. Which method is used to retrieve the value of an input field?

A. text()

B. html()

C. val()

D. append()

Correct Answer: C. val()

3. Which method inserts content at the end of an element's content?

A. prepend()

B. before()

C. append()

D. remove()

Correct Answer: C. append()

4. Which method removes all child content while keeping the selected element?

A. remove()

B. empty()

C. replaceWith()

D. clone()

Correct Answer: B. empty()

5. Which method inserts content immediately after the selected element?

A. append()

B. prepend()

C. before()

D. after()

Correct Answer: D. after()

6. Which method creates a copy of an element?

A. clone()

B. empty()

C. val()

D. text()

Correct Answer: A. clone()

Conclusion

jQuery HTML manipulation is an essential skill for creating dynamic and interactive webpages. Methods such as html(), text(), val(), append(), prepend(), before(), after(), remove() and empty() allow developers to work with webpage content using straightforward code.

By practising these methods, you can create interactive task lists, product displays, form interfaces and other dynamic website features.

←
Post 5 of 15
→