jQuery replaceWith() with Examples


The replaceWith() method in jQuery is used to replace selected elements with new content.

Syntax

The syntax is as follows −

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

Above, the content parameter is the content to insert, whereas function is to return the content to replace.

Example

Let us now see an example to implement the jQuery replaceWith() method 

 Live Demo

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $("button").click(function(){
         $("h2").replaceWith("<h2>This is it!</h2>");
      });
   });
</script>
</head>
<style>
div {
   margin: 10px;
   width: 60%;
   border: 2px dashed orange;
   padding: 5px;
   text-align:justify;
}
</style>
<body>
<div>
<h2>Demo Heading</h2>
<h2>Demo Heading</h2>
<h2>Demo Heading</h2>
<h2>Demo Heading</h2>
</div>
<p>Click the below button to update headings</p>
<button>Click</button>
</body>
</html>

Output

This will produce the following output −

Now, click the button to update headings −

Updated on: 31-Dec-2019

195 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements