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.
Are you working with mouse events then check the jQuery hover event tutorial which is made for beginners like you.

jQuery HTML Example 1: Set HTML of a div

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>");
});

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";
    });
}); 
Related: Developers should also know the related method which is the jQuery val method.

jQuery Html Example 3: Get html of a div

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:

DOWNLOAD

Next tutorial – jQuery Text Method – .text() – Complete Usage Guide with Codes

SHARE THIS ARTICLE

  • linkedin
  • reddit
yogihosting

ABOUT THE AUTHOR

I hope you enjoyed reading this tutorial. If it helped you then consider buying a cup of coffee for me. This will help me in writing more such good tutorials for the readers. Thank you. Buy Me A Coffee donate