.replaceAll()

Replace each target element with the set of matched elements.

.replaceAll(target)🡢 jQuery

target Selector, jQuery, Array, ElementA selector string, jQuery object, DOM element, or array of elements indicating which element(s) to replace.

The .replaceAll() method is similar to .replaceWith(), but with the source and target reversed. Consider this DOM structure:

<div class="container">
  <div class="inner first">Hello</div>
  <div class="inner second">And</div>
  <div class="inner third">Goodbye</div>
</div>

We can create an element, then replace other elements with it:

$("<h2>New heading</h2>").replaceAll(".inner");

This causes all of them to be replaced:

<div class="container">
  <h2>New heading</h2>
  <h2>New heading</h2>
  <h2>New heading</h2>
</div>

Or, we could select an element to use as the replacement:

$(".first").replaceAll(".third");

This results in the DOM structure:

<div class="container">
  <div class="inner second">And</div>
  <div class="inner first">Hello</div>
</div>

From this example, we can see that the selected element replaces the target by being moved from its old location, not by being cloned.

Replace all the paragraphs with bold words.

JS
<p>Hello</p>
<p>cruel</p>
<p>World</p>
HTML
$("<b>Paragraph. </b>").replaceAll("p");
DEMO

Looking for a Web Developer?

👋

Hi! I'm Basti, author of this site. If you are looking for a web developer with 15+ years of experience, holla at me!

Be it the good 'ol jQuery, vanilla JS or modern frameworks like Vue and Svelte, front- or backend, I can help you.

Just write me at jobs@jqapi.com :)