jQuery replaceWith() Method

The replaceWith() method removes selected elements from the DOM and puts new content in their place. It is a quick way to swap one element for another — the original disappears and the replacement takes its exact position.

Basic Syntax

$(selector).replaceWith(newContent);

// newContent can be:
// - An HTML string
// - An existing DOM element (selected with jQuery)
// - A function that returns HTML

Diagram: replaceWith() in Action

  Before:
  <p id="oldText">Old paragraph content</p>

  $("#oldText").replaceWith("<h3>New Heading!</h3>");

  After:
  <h3>New Heading!</h3>

  The <p> is gone. The <h3> is in its place.

Replace with HTML String

$(document).ready(function() {
    $("#plainBtn").replaceWith("<button id='fancyBtn' class='primary-btn'>Fancy Button</button>");
});

The old button element is removed from the DOM and replaced with a new styled button.

Replace with Existing Element

// Move an existing element to replace another
$(document).ready(function() {
    var newElement = $("<div class='alert'>Warning!</div>");
    $("#placeholder").replaceWith(newElement);
});

Replace with a Function

Pass a function to replaceWith() when the replacement depends on the original element's content or attributes.

$(document).ready(function() {
    $("p.convert").replaceWith(function() {
        var oldText = $(this).text();
        return "<h4>" + oldText + "</h4>";
    });
});

Diagram: Function-Based Replace

  Original:
  <p class="convert">Section Title</p>
  <p class="convert">Another Title</p>

  After replaceWith(function):
  <h4>Section Title</h4>
  <h4>Another Title</h4>

  Each <p> was read, its text extracted, and replaced with an <h4>.

replaceAll() — The Reverse Version

jQuery also has replaceAll(), which works in the opposite direction. Instead of "replace the selected element with this", it means "replace these targets with the selected element".

// replaceWith: take a target, replace it with something
$("#oldDiv").replaceWith("<div class='new'>New</div>");

// replaceAll: create something, then replace a target with it
$("<div class='new'>New</div>").replaceAll("#oldDiv");

// Both produce the same result.

Practical: Switch Between View and Edit Mode

HTML:
<p id="username-display">JohnDoe <a id="editName" href="#">[Edit]</a></p>

jQuery:
$(document).ready(function() {
    $(document).on("click", "#editName", function(e) {
        e.preventDefault();
        var currentName = "JohnDoe";
        var editField = '<span id="username-edit">' +
            '<input type="text" id="nameInput" value="' + currentName + '" />' +
            '<button id="saveName">Save</button>' +
            '<button id="cancelEdit">Cancel</button>' +
        '</span>';
        $("#username-display").replaceWith(editField);
    });

    $(document).on("click", "#saveName", function() {
        var newName = $("#nameInput").val();
        var display = '<p id="username-display">' + newName +
            ' <a id="editName" href="#">[Edit]</a></p>';
        $("#username-edit").replaceWith(display);
    });

    $(document).on("click", "#cancelEdit", function() {
        var display = '<p id="username-display">JohnDoe' +
            ' <a id="editName" href="#">[Edit]</a></p>';
        $("#username-edit").replaceWith(display);
    });
});

replaceWith() vs Other DOM Methods

MethodWhat HappensOriginal Kept?
replaceWith()Element is removed, new one inserted in its placeNo
html()Inner content replaced, element staysYes (element stays)
after()New content inserted after elementYes
before()New content inserted before elementYes

Important: Events Are Lost After replaceWith()

When you use replaceWith(), the original element is removed from the DOM along with all its event listeners. The replacement element starts fresh with no events. Use event delegation on a stable parent if you need the replacement to have events.

// Use delegation on a parent that stays in the DOM
$(document).on("click", "#editName", function() { ... });

Quick Summary

  • replaceWith(newContent) removes the selected element and inserts new content in its place.
  • New content can be an HTML string, a jQuery object, or a function.
  • replaceAll(target) is the reverse — it replaces the target with the selected content.
  • Events on the original element are lost after replacement.
  • Use event delegation so the replacement element's events keep working.

Leave a Comment

Your email address will not be published. Required fields are marked *