jQuery Introduction | Manipulating Elements | Replacing Elements .replaceAll() .replaceWith()
Replacing Elements
The following methods let you replace selected elements or content with specified elements or content.
| Method | Description |
|---|---|
| .replaceAll() | Replaces the selected element with the specified element. |
| .replaceWith() | Replaces all selected elements with the specified element. |
.replaceAll() Method
The .replaceAll() method replaces selected elements with the specified element.
This method can receive a selector, jQuery object, HTML DOM element, array, and more as an argument.
$(source).replaceWith(target);
When HTML elements exist as follows:
<p>Hello.</p>
<p>Nice to meet you.</p>
You can create an element and replace other elements with that element.
$("<div>This is devkuma.</div>").replaceAll("p");
Or you can replace another element with the element of an object.
$("#two").replaceAll($("#one"));
.replaceWith() Method
The .replaceWith() method replaces selected elements with the specified element.
This method can receive an HTML code string, jQuery object, HTML DOM element, array, and more as an argument.
It can also receive a function that returns content capable of replacing the selected element.
$(target).replaceWith(source);
The behavior of .replaceWith() is similar to .replaceAll(), but the positions of the source and target are reversed.
Also, .replaceWith() returns the existing elements that were removed after being replaced by the specified element.
When HTML elements exist as follows:
<p>Hello.</p>
<p>Nice to meet you.</p>
You can create an element and replace other elements with that element.
$("p").replaceWith("<div>This is devkuma.</div>");
Or you can replace another element with the element of an object.
$("#one").replaceAll($("#two"));
The
.replaceAll()and.replaceWith()methods also remove all data and event handlers related to the removed elements.