jQuery replaceAll() vs replaceWith()

Both the replaceAll() and replaceWith() methods in jQuery accomplish the same fundamental task: replacing selected DOM elements with new HTML, DOM elements, or jQuery objects. The primary distinction between the two methods lies in their syntax, specifically the reversal of the target and the replacement source, as well as the element set returned for method chaining.

Syntax and Placement

The most noticeable difference is the arrangement of the target elements versus the replacement content.

  • replaceWith() Syntax:
    $(target).replaceWith(replacementContent)
    With replaceWith(), the selector preceding the method identifies the existing elements in the document that you want to replace. The argument passed inside the method contains the new content.

  • replaceAll() Syntax:
    $(replacementContent).replaceAll(target)
    With replaceAll(), the selector preceding the method defines the new replacement content, while the argument passed inside the method specifies the existing target elements to be replaced.

Code Comparison

Consider the following HTML:

<div class="container">
  <p class="old-text">First paragraph</p>
  <p class="old-text">Second paragraph</p>
</div>

To replace both paragraphs with a <h2> heading using replaceWith():

$('.old-text').replaceWith('<h2>Updated Heading</h2>');

To achieve the exact same DOM modification using replaceAll():

$('<h2>Updated Heading</h2>').replaceAll('.old-text');

Differences in Chaining and Return Values

Another critical distinction is what each method returns, which impacts jQuery method chaining.

  • replaceWith() returns the replaced elements: It returns the original jQuery set (the elements that have just been removed from the DOM). Any chained methods will apply to the detached elements, not the new elements in the document.
  • replaceAll() returns the new elements: It returns the replacement elements that were inserted into the DOM. Subsequent chained methods will affect the newly added content.

Accepted Argument Types

The types of arguments each method accepts also vary slightly:

  • replaceWith() accepts HTML strings, DOM elements, jQuery objects, or a callback function that returns the replacement content dynamically for each matched element.
  • replaceAll() takes a selector expression, a jQuery object, or a DOM element representing the targets to be replaced. It does not accept a callback function.