Home » jquery » Replacing content of div using .replaceWith()

Replacing content of div using .replaceWith()

To replace the content of a div span or any other block elements content with html element a jquery method .replaceWith() is used.
Syntax:

or

A selector can be id class or tag selector of element to replace with newContent passed in .replaceWith() method. a newContent can be html string, DOM element, Array or object.
Another syntax uses any function that evaluates and replace the selector with new function return value.

There is a div with id value a with content Hi how are you. Here id a will replaced with div id with value b and content I am fine when ever user click on button.

Example:
Html page is

We want to replace <div id=”a”> with following content

To achive above with jquery we will use following code

Output:

Here new content will be

Lets use function in replaceWith method

Jquery code


.replaceWith() does not clone the object it replace the content on DOM.

Please follow and like us:
error