.text() and .html() in jQuery

I see developers getting confused on when to use the jQuery .text() vs .html() functions. So I thought of writing a simple demo to clear the confusion

.html() – gets or sets the HTML within a selected element. When you supply it a string with HTML, it renders the HTML. .html() cannot be used in in XML documents

.text() – gets or sets the Text within a selected element. Unlike .html(), .text() cannot alter the HTML. So if you supply a string containing HTML inside .text(), it will display the HTML (by converting elements with corresponding character entities) and not render it. However .text() can be used in both XML and HTML documents

Here’s an example

<html xmlns="http://www.w3.org/1999/xhtml" >
<
head>
<
title>.text() and .html() in jQuery from DevCurry.com</title>
<
style type="text/css">
.colorDiv { color:blue; }
</style>
<
script type="text/javascript"
src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.min.js"></script>

<
script type="text/javascript">
$(function () {

$("#btnHtml").click(function () {
$("#divOne")
.html('<span class="colorDiv">HTML and Content gets changed</span>');
});

$("#btnText").click(function () {
$("#divTwo").text('Only Content gets changed');
});

});

</script>
</
head>
<
body>
<
div id="divOne">This is a simple looking DIV</div><br />
<
div id="divTwo">This is another simple looking DIV</div><br />
<
input id="btnHtml" type="button" value=".html()" />
<
input id="btnText" type="button" value=".text()" />
</
body>
</
html>

As you can see, we are using two Div’s in our example. When the btnHtml is clicked, we use .html() to add a <span> element with class colorDiv and some new text in it. So we are able to change both the HTML and the Content using .html().

When the btnText is clicked, we are able to change only the text, since it’s not possible to change the HTML using .text()

See a Live Demo






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: