How does jQuery replaceWith() method work?

The replaceWith( content ) method replaces all matched elements with the specified HTML or DOM elements. This returns the jQuery element that was just replaced, which has been removed from the DOM.

Here is the description of all the parameters used by this method −

  • content − Content to replace the matched elements with.


You can try to run the following code to learn how to work with replaceWith() method:

Live Demo


      <title>jQuery replaceWith() method</title>
      <script src = ""></script>
         $(document).ready(function() {
            $("div").click(function () {
               $(this).replaceWith( ('<div class = "div"></div>') );
         .div {
             border:2px solid #666;
      <p>Click on any square below to see the result:</p>
      <div class = "div" style = "background-color:blue;">ONE</div>
      <div class = "div" style = "background-color:green;">TWO</div>
      <div class = "div" style = "background-color:red;">THREE</div>