tags:

views:

284

answers:

5

Using jQuery, what the difference between:

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

vs

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

The first example will actually embed HTML within the div whereas the second example will escape the text by means of replacing element-related characters with their corresponding character entities so that it displays literally (i.e. the HTML will be displayed not rendered).

Andrew Hare
Sorry, I don't quite understand. Could you further explain. Thanks
Brettk
What do you mean the 2nd example will "encode"? It's already encoding, no?
Brettk
@Brettk - I said "encode" but that was more a slip of the fingers. I changed my answer to better reflect what I mean.
Andrew Hare
He means that in the `.text()` function, all `<` will be replaced with `<`. So with `.html()` the browser will see a link and some bold text, with `.text()` the browser will see everything as text and not make a link or bold text.
fudgey
+9  A: 

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

<html>
<head>
  <title>Test Page</title>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"&gt;&lt;/script&gt;
  <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>

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

Peter Bailey
+1 for giving a test example
djangofan
+1, give that man a beer. oh, wait. he has one already.
Cheeso
+2  A: 

The text() method entity-escapes any HTML that is passed into it. Use text() when you want to insert HTML code that will be visible to people who view the page.

Technically, your second example produces:

&lt;a href="example.html"&gt;Link&lt;/a&gt;&lt;b&gt;hello&lt;/b&gt;

which would be rendered in the browser as:

<a href="example.html">Link</a><b>hello</b>

Your first example will be rendered as an actual link and some bold text.

davidcl
+1 For being the more explicit answer
T. Stone
A: 

Basically, $("#div").html uses element.innerHTML to set contents, and $("#div").text (probably) uses element.textContent.

http://docs.jquery.com/Attributes/html:

Set the html contents of every matched element

http://docs.jquery.com/Attributes/text:

Similar to html(), but escapes HTML (replace "<" and ">" with their HTML 
entities).
Seth
+1  A: 

$('.div').html(val) will set the HTML values of all selected elements, $('.div').text(val) will set the text values of all selected elements.

API docs for jQuery.text()

API docs for jQuery.html()

I would guess that they correspond to Node#textContent and Element#innerHTML, respectively. (Gecko DOM references).

Michiel Kalkman