jQuery Tutorial Tutorials - jQuery .replaceWith() method

jQuery .replaceWith() method

The .replaceWith(newContent) method in jQuery is used to replace matched element's content with newContent.

jQuery .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.

jQuery .replaceWith() method Example

example

Replace 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>

Try now

example

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>

jQuery .replaceWith(function)

Generating a random integer using JavaScript

$('button').click(function(){
    $('.container').replaceWith(function(){
        return '<div class="container">'+ Math.round(Math.random() * 100) + '</div>';
    });
});

Try now

Date:2019-08-25 10:31:40 From:www.Lautturi.com author:Lautturi