In example # 1, we have attached an event handler to the element with the id: “foo”. I think you’ll find that it’s pretty tedious. If you don’t believe me, go ahead and try this yourself using just vanilla JavaScript. You really do have to thank the folks from jQuery, for packing a great deal of abstraction into this one method.
And what makes this method so helpful is the expressive syntax on a high-level, it’s a simple as A.replaceWith(B). You simply specify the original section of the DOM as well as the new chunk, and then jQuery takes care of all the work. 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.
#Javascript replacewith how to
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. Now this may sound simple, but with vanilla JavaScript, this kind of work can get pretty tedious. One example is replacing one DOM element with another. But just be aware… there are other tasks that come up, and some of them can get rather messy. In fact, jQuery is so helpful in this context, it’s hard to argue against using it for your event handling / delegation. Most of the time, jQuery is used to add click event handlers to DOM elements, and there’s nothing wrong with this. The replaceWith() method provides a way to completely remove an element and put another in its place