jQuery Html Method – .html() – Complete Usage Guide with Codes

jQuery Html Method – .html() – Complete Usage Guide with Codes

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

$(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)) 
  • 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.

<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.

<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.

<div id="div3">Welcome <br/> coder!</div>
<button id="button3">Get Value</button>

$("#button3").click(function (e) {
    alert($("#div3").html());
}); 

DEMO DOWNLOAD

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "WordPress, SEO, jQuery, HTML" and more.