Jquery – the difference between jQuery: text() and html()

domjquery

What the difference between text() and html() functions in jQuery ?

$("#div").html('<a href="example.html">Link</a><b>hello</b>');

vs

$("#div").text('<a href="example.html">Link</a><b>hello</b>');

Best Answer

I think the difference is nearly self-explanatory. And it's super trivial to test.

jQuery.html() treats the string as HTML, jQuery.text() treats the content as text

<html>
<head>
  <title>Test Page</title>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
  <script type="text/javascript">
    $(function(){
      $("#div1").html('<a href="example.html">Link</a><b>hello</b>');
      $("#div2").text('<a href="example.html">Link</a><b>hello</b>');
    });
  </script>
</head>

<body>

<div id="div1"></div>
<div id="div2"></div>

</body>
</html>

A difference that may not be so obvious is described in the jQuery API documentation

In the documentation for .html():

The .html() method is not available in XML documents.

And in the documentation for .text():

Unlike the .html() method, .text() can be used in both XML and HTML documents.

$(function() {
  $("#div1").html('<a href="example.html">Link</a><b>hello</b>');
  $("#div2").text('<a href="example.html">Link</a><b>hello</b>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<div id="div1"></div>
<div id="div2"></div>
Live demo on http://jsfiddle.net/hossain/sUTVg/