How jQuery Replace HTML Content of an Element

Last Updated on June 20, 2021 by Roshan Parihar

In this tutorial, learn how to replace HTML content of an element using jQuery. The short answer is to use the html() method that takes the HTML element as the argument to pass.

You can also use the replaceWith() of jQuery to change the HTML content of the element. Let’s find out with the examples given below to learn the methods.

Method 1: Using html() to Replace HTML Content in jQuery

The function replaces the inner content of the selected HTML element. However, you can add HTML tags inside the html() to replace them with the selected HTML element.

To learn more about the syntax of html() function, you can read our post on jQuery html().

Output


This is a paragraph with HTML content.

You can click the above-given button to replace HTML content using jQuery html().

The above example replaces HTML content using jQuery for the selected HTML paragraph tag using the id. The replaced content contains the HTML span tag and HTML strong tag.

Method 2: Using replaceWith() to Change HTML Content in jQuery

In addition to the above method, you can also use the replaceWith() function to change the HTML content. However, it replaces the inner content of the HTML element. See the below example to learn how to do this.

Output


This is a paragraph with HTML content.

When you click the button given above, it replaces the inner content of the HTML element and not the whole HTML tag. The above example replaces the HTML element paragraph with the specified HTML content in the script.

The main difference between these two functions is that html() can replace the whole HTML element and jQuery replaceWith() replaces inner HTML element content.

Looking for more examples? Click below-given examples to see each one.

List of Examples

Output


This is my paragraph.

Output


Hello World

Welcome to the Tutorialdeep web tutorial.

Learn new things each day.