To replace the content of a div span or any other block elements content with html element a jquery method .replaceWith() is used.
Syntax:
1 | $(selector).replaceWith(newContent); |
or
1 | $(selector).replaceWith(function); |
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
1 2 3 4 5 6 7 8 9 10 | <div class="one"> <div id="a"> Hi How are you </div> <button id="replace"> Replace Content </button> </div> |
We want to replace <div id=”a”> with following content
1 2 3 | <div id="b"> I am fine. </div> |
To achive above with jquery we will use following code
1 2 3 4 5 6 7 8 9 | $(document).ready(function() { $(document).on('click', '#replace', function(event) { event.preventDefault(); $("#a").replaceWith(" <div id="\"b\"">I am fine.</div> "); }); }); |
Output:
Here new content will be
1 2 3 4 5 6 7 8 9 10 | <div class="one"> <div id="b"> I am fine. </div> <button id="replace"> Replace Content </button> </div> |
Lets use function in replaceWith method
1 2 3 4 5 6 7 8 9 10 11 12 | <h1 class="test"> <div id="a">Good to read this</div> </h1> <div id="b">Better to practice now</div> <button id="replace"> Replace Content </button> |
Jquery code
1 2 3 4 5 6 7 | $(document).ready(function() { $(document).on('click', '#replace', function(event) { event.preventDefault(); $("#a").replaceWith($('#b"); }); }); |
.replaceWith() does not clone the object it replace the content on DOM.