Home >>jQuery Tutorial >jQuery replaceWith() Method

jQuery replaceWith() Method

jQuery replaceWith() Method

jQuery replaceWith() method in jQuery is an inbuilt method which is used to replaces selected elements with new content.

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

Parameter Values

Parameter Description
Content It is a required parameter used to insert the specified content

Possible values:

  • jQuery objects
  • HTML elements
  • DOM elements
function(index) It is optional parameter which is used to replace the specifies content
  • index – this parameter is used to returns the index position
Here is an Example of jQuery replaceWith() Method:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".btn1").click(function(){
$(".txt:first").replaceWith("Hello Phptpoint!");
});
});
</script>
</head>
<body>
<p class="txt">This is First paragraph.</p>
<p class="txt">This is Second paragraph.</p>
<button class="btn1">Replace the first element with new text</button>
</body>
</html>

Output:

This is First paragraph.

This is Second paragraph.