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.
The .html() method has 3 syntaxes.
1. For Returning Html
$(selector).html()
2. For Setting Html
$(selector).html("<b>Wow!</b> <span class='color: Red'>great job</span>")
3. For Setting Html through a Function
$(selector).html(function(index,currentvalue))
I have one div and a button. On the button click, the html contents of the div is set.
I will be placing a text and a button inside this div.
This code is shown below.
<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>");
});
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.
<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";
});
});
The below code alerts the html of the div element when the button is clicked.
<div id="div3">Welcome <br/> coder!</div>
<button id="button3">Get Value</button>
$("#button3").click(function (e) {
alert($("#div3").html());
});
The link to download the source code is below: