Difference between jQuery text() and html() functions

jQuery provides 2 functions text() and html() and when to use text() function and when to use html() function is quite confusing as both the functions are different and serve different purpose.

.html() - This jQuery function gets/sets the HTML of any element.
.text()- This jQuery function gets/sets the text (innertext) of any element.

Let's take an example. I have placed a div element, which have a span tag as child and some text.

<div id="dvFirst">
    <span>jQuery By Example </span>

Now in .ready() event, both the functions .html() and .text() functions are used on div and the output is placed in alert box.

$(function () {          
    alert("Div HTML is: " + $("#dvFirst").html());
    alert("Div content is: " + $("#dvFirst").text());

Now, when you view this page in browser, there will be 2 alerts.

First alert box, will display below text.
Div HTML is: <span>jQuery By Example </span>

And second alert box, will display below text.
Div content is: jQuery By Example

As you see, that the .html() function provides you the inner html and text of the element while text function gives you only text.

See live Demo and Code.

One thing to note, that while using the text() function and if you have supplied any HTML markup then it will be treated as text only.

$(function () {       
    $("#dvFirst").text("I am new content of div");

Above code will treat the span as text. It will not be considered as HTML.

See live Demo and Code.

Read about:

Feel free to contact me for any help related to jQuery. I will gladly help you.