It provides various methods to achieve this functionality but the one we are going to look at in this post is the JQuery’s replacewith() method.
Let’s take a deep look at this method.
JQuery replaceWith() Method
In jQuery, the replaceWith() function is used to replace chosen components with new ones and it returns the components that have been replaced.
The replaceWith() method syntax is mentioned below.
Arguments Explanation
Here’s the explanation of the arguments of replacewith() method
- newContent: It is the content that will be used to replace the parts that have been chosen.
- (idx)=>{}: It’s the function that returns the replacement content. It also has an index of arguments and this index parameter is used to return the index position of the element.
To better understand how to utilize the replaceWith() function, consider the following examples.
Example #1
Suppose, we have a <div> element in our HTML whose id is “element1” and at the click of a button we want to replace it with the <p> tag.
The HTML part would be like this:
And at the click of a button, we want to replace the <div>
Now, to completely convert the <div> tag and its content to the <p> tag, jQuery’s code will go like this:
$("#btn").click(function() {
$("#element1").replaceWith("<p> Element Replaced :) </p>");
});
});
In the above example, we are simply first fetching the HTML element by using the IDs of the button and div tag and then replacing the <div> tag with the <p> tag using replaceWith() method.
Output
You can witness that the element was successfully replaced.
Conclusion
JavaScript’s replacewith() method is used to replace one HTML element with some other element according to the requirement. This replacewith() method takes two arguments, the first argument is the content that you want to be replaced with while the second argument is used to return the index position of the content that you want to replace with. In this article, we have discussed the examples of replacing the old content with the new one using JQuery.