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>');
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>');
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).
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"></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>
jQuery.html()
treats the string as HTML, jQuery.text()
treats the content as text.
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:
<a href="example.html">Link</a><b>hello</b>
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.
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).
$('.div').html(val) will set the HTML values of all selected elements, $('.div').text(val) will set the text values of all selected elements.
I would guess that they correspond to Node#textContent and Element#innerHTML, respectively. (Gecko DOM references).