jQuery replaceWith()

Introduction

Replace the first <p> element with new text:

View in separate window

<!DOCTYPE html>
<html>
<head>
<script 
 src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>/* w w  w . j  a va2  s.com*/
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("p:first").replaceWith("Hello world!");
  });
});
</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>

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

$(selector).replaceWith(content,function(index))
Parameter
Optional
Description
content




Required.




Specifies the content to insert
Possible values:
HTML elements
jQuery objects
DOM elements
function(index)

Optional.

sets a function that returns the content to replace
index - the index position of the element in the set



PreviousNext

Related