jQuery replaceWith() method can be used to replace the element with the specified content. It replaces all the elements matching with the selected element.
Syntax
The syntax of this method is given below:-
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
1 2 3 4 5 6 7 8 9 |
<script> $(document).ready(function(){ $('.mybtn').click(function(){ $("p").replaceWith("<b>Learn jQuery from TutorialDeep!</b>"); }); }); </script> <p>This is my paragraph.</p><br> <button type="button" class="mybtn">Click to Replacewith</button> |
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
1 2 3 4 5 6 7 8 9 10 11 |
<script> $(document).ready(function(){ $('.mybtnfn').click(function(){ $("p").replaceWith(function(){ return "<em>See live example to Learn jQuery</em>" }); }); }); </script> <p>This is my paragraph.</p><br> <button type="button" class="mybtnfn">Click to Replacewith</button> |
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