JavaScript LogoThe replaceWith() method provides a way to completely remove an element and put another in its place

Most of the time, jQuery is used to add click event handlers to DOM elements, and there’s nothing wrong with this. In fact, jQuery is so helpful in this context, it’s hard to argue against using it for your event handling / delegation. But just be aware… there are other tasks that come up, and some of them can get rather messy. One example is replacing one DOM element with another. Now this may sound simple, but with vanilla JavaScript, this kind of work can get pretty tedious. Normally, I recommend learning how to do things with vanilla JavaScript that you would want to do with jQuery, but there are times when this kind of wheel reinvention becomes a bad idea.

So, this is where the jQuery replaceWith() method comes in; it allows you to chop out one piece of the page and replace it with another. You simply specify the original section of the DOM as well as the new chunk, and then jQuery takes care of all the work. And what makes this method so helpful is the expressive syntax; on a high-level, it’s a simple as A.replaceWith(B). You really do have to thank the folks from jQuery, for packing a great deal of abstraction into this one method. If you don’t believe me, go ahead and try this yourself using just vanilla JavaScript. I think you’ll find that it’s pretty tedious.

Example # 1

In example # 1, we have attached an event handler to the element with the id: “foo”. When clicked, that element is removed from the page, and replaced with a piece of markup defined in a string. Yes, it’s that easy, and there are certainly more interesting things you can do with this jQuery method.


Replacing one section of the page with another piece of markup is quite easy with the jQuery replaceWith() method. The syntax is very straight-forward and if you are already familiar with jQuery, there are quite a few possibilities.

Helpful links for the jQuery replaceWith method