replaceWith() Method - Javascript jQuery Method and Property

Javascript examples for jQuery Method and Property:replaceWith

Description

The replaceWith() method replaces selected elements with new content.

Syntax

Parameter Require Description
content Required.HTML elements/jQuery objects/DOM elements content to insert
function(index) Optional.a function that returns the content to replace
  • index - the index position of the element in the set

The following code shows how to Replace the first <p> element with new text:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("p:first").replaceWith("Hello world!");
    });/*w ww.j  a v a  2s .c  o m*/
});
</script>
</head>
<body>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

<button>Replace the first p element with new text</button>

</body>
</html>

Related Tutorials