🔥 $100K Hit! Where Will Bitcoin Go Next? Find Out Live!

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:

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.