jQuery replaceWith() Method

jQuery replaceWith() method replaces selected elements with the new content.

jQuery replaceWith() method is similar to replaceAll() method, but there is one difference is in the syntax, placement of the content and target element.

Syntax

Here is a syntax for the replaceWith() method

$(selector).replaceWith( content, function(index) );
Parameter Type Description
content htmlString
Element
Text
Array
jQuery
Required. HTML string, DOM element, text node, array of elements, or jQuery object that replace to selected elements.
function(index) Function Optional. A function that returns an HTML string, DOM element, text node, array of elements, or jQuery object that replace to selected elements.
  • index - Return the index position of the element in the set as an argument.

Example

Here, in this example replaceWith() method call on selected elements when click on button.

<!DOCTYPE html>
<html>
<head>
  <title>jQuery replaceWith() method</title>
  <script src="jquery-latest.min.js"></script>
  <script>
    $(document).ready(function(){
      $("button").click(function(){
        $(".second").replaceWith("<h3>Heading text</h3>");
      });
    });
  </script>
</head>
<body>
  <div>
    <p class="param first">First paragraph start here...</p>
    <p class="param second">Second paragraph start here...</p>
    <p class="param third">Third paragraph start here...</p>
  </div>
  <button>Click here to call replaceWith() method</button>
</body> 
</html>

Run it...   »