Difference between jQuery text() and html() functions
.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> </div>
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.
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.
Read about:
- text() function in jQuery
- How to get HTML of any control using jQuery
- How to set HTML of any control using jQuery
Feel free to contact me for any help related to jQuery. I will gladly help you.