.replaceWith()
methodThe .replaceWith(newContent)
method in jQuery is used to replace matched element's content with newContent
.
.replaceWith()
method Syntax.replaceWith(newContent) .replaceWith(function)
Parameter | Type | Description |
---|---|---|
newContent |
htmlString,element,Array,jQuery | The new content to replace with. |
function() |
Function | A function returning the content to replace with. |
.replaceWith()
method ExampleReplace the paragraphs with a new created element.
HTML
<div class="container"> <p>Learn JavaScript</p> <p>Learn jQuery</p> Lautturi tutorial </div>
jQuery
$('p').replaceWith('<b>Learning online</b>');
Result
<div class="container"> <b>Learning online</b> <b>Learning online</b> Lautturi tutorial </div>
Replace paragraphs with an selected element.
Please note that the selected element is moved from its old location but not cloned.
HTML
<div class="container"> <p class="js">Learn JavaScript</p> <p class="cpp">Learn C++</p> <p class="jquery">Learn jQuery</p> </div>
jQuery
$('.jquery').replaceWith('.js');
Result
<div class="container"> <p class="cpp">Learn C++</p> <p class="js">Learn JavaScript</p> </div>
.replaceWith(function)
Generating a random integer using JavaScript
$('button').click(function(){ $('.container').replaceWith(function(){ return '<div class="container">'+ Math.round(Math.random() * 100) + '</div>'; }); });