300

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>');
1

17 Answers 17

362

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/

2
  • It should be noted too, that the length is different between the two as well. jsfiddle.net/sUTVg/458
    – Katrina
    May 20, 2015 at 16:50
  • 5
    @aequalsb I recognise that this is an old question now, but I have to remark that defaulting to using ´.html()´ is dangerous because of the text being treated as HTML. If you get that text from a querystring parameter, form, header, the URL or any other place that someone else than you can supply or edit the text, then you are wide open for XSS.
    – Canis
    Oct 12, 2017 at 18:35
110

((please update if necessary, this answer is a Wiki))

Sub-question: when only text, what is faster, .text() or .html()?

Answer: .html() is faster! See here a "behaviour test-kit" for all the question.

So, in conclusion, if you have "only a text", use html() method.

Note: Doesn't make sense? Remember that the .html() function is only a wrapper to .innerHTML, but in the .text() function jQuery adds an "entity filter", and this filter naturally consumes time.


Ok, if you really want performance... Use pure Javascript to access direct text-replace by the nodeValue property. Benchmark conclusions:

  • jQuery's .html() is ~2x faster than .text().
  • pure JS' .innerHTML is ~3x faster than .html().
  • pure JS' .nodeValue is ~50x faster than .html(), ~100x than .text(), and ~20x than .innerHTML.

PS: .textContent property was introduced with DOM-Level-3, .nodeValue is DOM-Level-2 and is faster (!).

See this complete benchmark:

// Using jQuery:
simplecron.restart(); for (var i=1; i<3000; i++) 
    $("#work").html('BENCHMARK WORK');
var ht = simplecron.duration();
simplecron.restart(); for (var i=1; i<3000; i++) 
    $("#work").text('BENCHMARK WORK');
alert("JQuery (3000x): \nhtml="+ht+"\ntext="+simplecron.duration());

// Using pure JavaScript only:
simplecron.restart(); for (var i=1; i<3000; i++)
    document.getElementById('work').innerHTML = 'BENCHMARK WORK';
ht = simplecron.duration();
simplecron.restart(); for (var i=1; i<3000; i++) 
    document.getElementById('work').nodeValue = 'BENCHMARK WORK';
alert("Pure JS (3000x):\ninnerHTML="+ht+"\nnodeValue="+simplecron.duration());
5
  • 9
    But if dealing with untrusted input, you should use text() whenever possible. Aug 31, 2015 at 15:15
  • @ScottSimontis when you set nodeValue property, it transforms ">" into "&lt;", etc. Aug 31, 2015 at 20:09
  • When I "benchmark" with Chrome DevTools (developer.chrome.com/devtools/docs/timeline), the result is opposite (.text() seems ~7x faster than .html()). Source code: codepen.io/damhonglinh/pen/vGpQEO. I tested with 1500 elements; .html() took ~220ms and .text() took ~30ms.
    – Linh Dam
    Apr 8, 2016 at 18:19
  • Hi @LinhDam. Hum... using the complete benchmark, my Firefox say "JQ TIMES (3000x): html=82 text=254", "JS TIMES (3000x): html=15 text=4"... And my Chrome say "JQ TIMES (3000x): html=82 text=202", "JS TIMES (3000x): html=16 text=0".... so both (Firefox and Chrome) have the same time ratios. Apr 9, 2016 at 19:15
  • to be a real benchmark between text() and html() the selector should be done or getElementById or $("#work") in all cases or you will be benchmarking also the $("#work") vs getElementById
    – Octavioamu
    Jan 25, 2019 at 15:08
68

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).

4
  • 1
    Sorry, I don't quite understand. Could you further explain. Thanks
    – Brettk
    Dec 15, 2009 at 22:20
  • What do you mean the 2nd example will "encode"? It's already encoding, no?
    – Brettk
    Dec 15, 2009 at 22:21
  • @Brettk - I said "encode" but that was more a slip of the fingers. I changed my answer to better reflect what I mean. Dec 15, 2009 at 22:22
  • 6
    He means that in the .text() function, all < will be replaced with &lt;. 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.
    – Mottie
    Dec 15, 2009 at 22:25
63

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.

1
  • 5
    This should have been included in the selected answer to explain what is really going on.
    – d512
    Feb 28, 2013 at 16:04
29

Actually both do look somewhat similar but are quite different it depends on your usage or intention what you want to achieve ,

Where to use:

  • use .html() to operate on containers having html elements.
  • use .text() to modify text of elements usually having separate open and closing tags

Where not to use:

  • .text() method cannot be used on form inputs or scripts.

    • .val() for input or textarea elements.
    • .html() for value of a script element.
  • Picking up html content from .text() will convert the html tags into html entities.

Difference:

  • .text() can be used in both XML and HTML documents.
  • .html() is only for html documents.

Check this example on jsfiddle to see the differences in action

Example

2
  • 2
    This answer was the easiest to understand and best formatted +1
    – Katie
    Sep 12, 2018 at 16:57
  • What is the diff bw :: html(data); & val(data); @Owais Qureshi
    – Gem
    May 9, 2019 at 9:39
12

Strange that no-one mentioned the Cross Site scripting prevention benefit of .text() over .html() (Although others have just mentioned that .text() escapes the data).

It's always recommended to use .text() when you want to update data in DOM which is just data / text for the user to see.

.html() should be mostly used to get the HTML content within a div.

5

Use .text(…) when you intend to display the value as a simple text.

Use .html(…) when you intend to display the value as a html formatted text (or HTML content).

You should definitely use .text(...) when you’re not sure that your text (e.g. coming from an input control) do not contain characters/tags that has special meaning in HTML. This is really important because this could result in the text will not display properly but it could also cause that an unwanted JS script snippet (e.g. coming from another user input) to be activated.

4

.text() will give you the actual text in between HTML tags. For example, the paragraph text in between p tags. What is interesting to note is that it will give you all the text in the element you are targeting with with your $ selector plus all the text in the children elements of that selected element. So If you have multiple p tags with text inside the body element and you do a $(body).text(), you will get all the text from all the paragraphs. (Text only, not the p tags themselves.)

.html() will give you the text and the tags. So $(body).html() will basically give you your entire page HTML page

.val() works for elements that have a value attribute, such as input. An input does not have contained text or HTML and thus .text() and .html() will both be null for input elements.

3

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).
2

$('.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).

1

Well in simple term.

html()-- to get inner html(html tags and text).

text()-- to get only text if present inside(only text)

2
  • 1
    html( ) & html(htmlString) are two distinct methods. The former returns the innerHTML of the first element in the set of matched elements. The latter sets the content of each matched element. api.jquery.com/html. Clearly the question asks about the latter. Same goes for text( ) & text(text).
    – Bohao LI
    Feb 4, 2021 at 21:05
  • These methods are quite confusing because the setting & getting methods have the same name, the only difference is the parameter. They really should have some more meaningful names like getInnerHTML / setInnerHTMLForAll or something.
    – Bohao LI
    Feb 5, 2021 at 13:37
1

The different is .html() evaluate as a html, .text() avaluate as a text.
Consider a block of html
HTML

<div id="mydiv">
<div class="mydiv">
    This is a div container
    <ul>
      <li><a href="#">Link 1</a></li>
      <li><a href="#">Link 2</a></li>
    </ul>
    a text after ul
</div>
</div>

JS

var out1 = $('#mydiv').html();
var out2 = $('#mydiv').text();
console.log(out1) // This output all the html tag
console.log(out2) // This is output just the text 'This is a div container Link 1 Link 2 a text after ul'

The illustration is from this link http://api.jquery.com/text/

0

I think that the difference is to insert html tag in text() you html tag do not functions

$('#output').html('You are registered'+'<br>'  +'  '
                     + 'Mister'+'  ' + name+'   ' + sourname ); }

output :

You are registered <br> Mister name sourname

replacing text() with html()

output

You are registered
Mister name sourname 

then the tag <br> works in html()

1
  • 1
    Please correct your answer, the first snippet should use text().
    – MKaama
    Aug 19, 2017 at 8:54
0

text function set or retrieve the value as plain text, otherwise, HTML function set or retrieve the value as HTML tags to change or modify that. If you want to just change the content then use text(). But if you need to change the markup then you have to use hmtl().

It's a dummy answer for me after six years, Don't mind.

0
**difference between text()&& html() && val()...?
#Html code..
<select id="d">
<option>Hello</option>
<option>Welcome</option>
</select>
# jquery code..
$(document).ready(function(){
   $("#d").html();
   $("#d").text();
   $("#d").val();

});
0

Whenever possible use .text() as it escapes the HTML, especially if you are adding any untrusted data such as from user input. .html() has some xss vulnerabilities

-2
var v = "&#x5168;&#x540D;";
$("#div").html(v); //display as "全名"
$("#div").text(v); //display as "&#x5168;&#x540D;"

text() – This method sets or returns the text content of elements selected. html() – This method sets or returns the content of elements selected. Refer example here : https://www.tutorialspoint.com/online_jquery_editor.php

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.