jQuery replaceWith: Main Tips
- Similarly to .replaceAll(), jQuery
.replaceWith()
removes specified elements and replaces them with new content. - The method makes jQuery replace HTML content and return the replaced elements.
Learn About .replaceWith()
Using jQuery .replaceWith()
replaces selected elements with new HTML content. In the example below, you can see it replace the text in the last <p>
element:
Example
$("button").click(() => {
$("p:last").replaceWith("Hello world!");
});
jQuery replace HTML method follows this syntax:
$(selector).replaceWith(content);
Instead of content
, you can also add a function
, delivering the content to replace the specified elements:
$(selector).replaceWith(function);
Note: by using jQuery replace element function, you get rid of the data and events related to deleted nodes.