Javatpoint Logo
Javatpoint Logo

jQuery replaceWith() method

The replaceWith() method in jQuery is used to replace the selected elements with the new one.  This method replaces the matched elements with the specified HTML elements. It returns the replaced elements. This method is similar to the replaceAll() method.

Syntax

Parameter values

The parameter values of the replaceWith() method are defined as follows.

newContent: It is a required parameter. It is the content to replace the selected elements. It can be HTML elements, DOM elements, or jQuery objects.

function(index): It is an optional parameter. It is the function that returns the content to replace. It includes an argument index. The index argument is used to return the element's index position.

Let's see some examples to understand how to use the replaceWith() method.

Example1

In this example, there are two div elements, a paragraph element, and a button on which we are applying the replaceWith() method. Here we are using the newContent parameter of the replaceWith() method.

After clicking the button, the div element with id = "d1" gets replaced with the heading h1, and the div element with id = "d2" gets replaced with the heading h2. The text of paragraph element with id = "p1" gets replaced with the new content, and the button with id = "btn" gets replaced with a new div element with id = "d3".

Test it Now

Output:

After the execution of the above code, the output will be -

jQuery replaceWith() method

After clicking the given button, the output will be -

jQuery replaceWith() method

Now, in the next example, we will use the function(index) parameter of the replaceWith() method.

Example2

In this example, there are some paragraph elements and some div elements. We are applying the replaceWith() method on all div elements and on the paragraph elements with class = "para". After clicking the given button, the paragraph elements with corresponding class gets replaced with the heading h4 and the div elements gets replaced with the heading h3.

Here, we are using the function(index) parameter of the replaceWith() function. In the output we can see the index position of the elements.

Test it Now

Output:

After the execution of the above code, the output will be -

jQuery replaceWith() method

After clicking the given button, the output will be -

jQuery replaceWith() method




Youtube For Videos Join Our Youtube Channel: Join Now

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA