Jquery html method

html() is used to get or set the html content in matched selector.
Getting content using html()

Html() get contents with html tags of specified selector

If more then one elements are there with same selector then only first matched elements content are get using html().

for setting html content we pass string argument in html()

setting html content using html()

we can set more then one selector value by html().

using function in html()

Jquery toggle an element

toggle is a method which is used to show and hide the selected class. if select element is hidden then on toggle it will show element.
If element is not hidden on toggle it will hide the element.

Output

We can also specify the toggle time and function to perform task of toggle done

Output

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.