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.

Latest Udacity Coupon Found:

Verified STAFF PICK

75% OFF COURSES

Udacity Black Friday Offer

The best time to save on Udacity courses is now - follow this coupon to access a 75% Udacity Black Friday discount & enjoy learning at a very low cost!

Expiration date: 22/01/2021
3176 People Used
Only 97 Left
Rating
5.0