jQuery replaceWith() Method

jQuery replaceWith() method can be used to replace the element with the specified content. It replaces all the elements matching with the selected element.

jQuery replaceWith() Method

Syntax

The syntax of this method is given below:-

Syntax
$(selector).replaceWith(content, function(index))

Description of the Parameters

The description of these parameters is given below.

Parameter Name Description
selector Specify the element to select and replace it with the new elements. You can use the element tag name, class name, or id to select. It is a required field.
content You have to specify the content to replace it with the selected element. It is an HTML tag or element that can contain some text content. It is a required field.
index It returns the index position of the element.

jQuery replaceWith() Method to Replace With the Specified Content

If you want to replace the selected element with the specified content, you have to use the method as given below. The example replace the paragraph with the specified bold element. The method takes the parameter as the content to replace with the selected element.

Example

Test it Live

Output

This is my paragraph.


You have to click the button given above to replace the content. The bold text in the output after button click showing new content replace with the old.

Use Function to Replace Element With the Specified Element

The method can also be used with the function to replace the element. You have to use the method as given in the example below.

Example

Test it Live

Output

This is my paragraph.


When you click the button given above, it replaces the old content with the new em element. The above output after button click showing the italic content after replacement.

You may also like to read

I hope you like this tutorial on jQuery replaceWith() method. If you have any queries regarding the tutorial, please comment below.

References