jQuery Method to Replace an Element With New Content

This article explains how to replace an existing DOM element with new content using jQuery. You will learn about the primary method, .replaceWith(), its inverse counterpart, .replaceAll(), and how to use them effectively with practical code examples.

The .replaceWith() Method

The primary jQuery method used to replace a target element with new content is .replaceWith(). This method removes the matched element (or elements) from the DOM and inserts new HTML string, DOM elements, or jQuery objects in its place.

Syntax

$(selector).replaceWith(newContent);
  • selector: The target element you want to remove and replace.
  • newContent: The content to insert. This can be an HTML string, a DOM element, an array of elements, or a jQuery object.

Example

Consider the following HTML:

<div class="container">
  <button id="old-button">Click Me</button>
</div>

To replace the <button> with a simple text paragraph, run the following jQuery code:

$('#old-button').replaceWith('<p>The button has been replaced.</p>');

The resulting HTML structure will be:

<div class="container">
  <p>The button has been replaced.</p>
</div>

Using a Function with .replaceWith()

You can also pass a callback function to .replaceWith() to dynamically return the replacement content.

$('div.item').replaceWith(function() {
  return '<span>' + $(this).text() + '</span>';
});

The Alternative: .replaceAll()

The .replaceAll() method performs the exact same task as .replaceWith(), but the syntax is reversed. Instead of selecting the target element first, you select or define the new content first and specify the target as the argument.

Syntax

$(newContent).replaceAll(targetSelector);

Example

Using the same initial HTML:

$('<p>The button has been replaced.</p>').replaceAll('#old-button');

Key Differences to Keep in Mind

  • Return Values: .replaceWith() returns the jQuery object containing the original element that was removed. In contrast, .replaceAll() returns the jQuery object containing the newly inserted element.
  • Event Handlers: When an element is replaced, any data and event handlers bound directly to the original element are removed along with it. Delegated event handlers attached to a parent element will continue to work for the new element if it matches the delegated selector.