The jQuery Html method (.html()) is used to either return or set the html contents of the selected elements.
For Returning – It returns the first matched element’s html content.
For Setting – It sets the html contents of all matched elements.
jQuery HTML Syntax
The .html() method has 3 syntaxes.
1. For Returning Html
1
| $(selector).html() |
2. For Setting Html
1
| $(selector).html("<b>Wow!</b> <span class='color: Red'>great job</span>") |
3. For Setting Html through a Function
1
| $(selector).html(function(index,currentvalue)) |
- index: returns the index of the element in the set.
- currentvalue: returns the html content of the element in the set.
Let us see some jQuery .html() examples to understand it’s working.
jQuery HTML Example 1: Set HTML of a div
I have one div and a button. On the button click, the html of the div is set.
I will be placing a text and a button inside this div.
This code is shown below.
1
2
3
4
5
| <div id="div1">Welcome</div><button id="button1">Set HTML</button>$("#button1").click(function (e) { $("#div1").html("Hi <button>New Button</button> <span style='color: Red'>created</span>");}); |
jQuery HTML Example 2: Set html of div using function
This time my div has an initial html content as ‘Welcome’.
I will add a button, a br tag and some text using .html() function parameter.
1
2
3
4
5
6
7
8
| <div id="div2">Welcome</div><button id="button2">Set HTML</button>$("#button2").click(function (e) { $("#div2").html(function (index, currentvalue) { return currentvalue + " <button>New Button</button> <br/> created"; });}); |
jQuery Html Example 3: Get html of a div
The below code alert the html of the div when the button is clicked.
1
2
3
4
5
6
| <div id="div3">Welcome <br/> coder!</div><button id="button3">Get Value</button>$("#button3").click(function (e) { alert($("#div3").html());}); |

