🚨 Time is Running Out: Reserve Your Spot in the Lucky Draw & Claim Rewards! START NOW

Code has been added to clipboard!

jQuery .replaceWith(): Delete Elements & Replace Them With New Content

Reading time 1 min
Published Jan 23, 2018
Updated Oct 1, 2019

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:

$("button").click(() => {
     $("p:last").replaceWith("Hello world!");

jQuery replace HTML method follows this syntax:


Instead of content, you can also add a function, delivering the content to replace the specified elements:


Note: by using jQuery replace element function, you get rid of the data and events related to deleted nodes.