By Brettk


2009-12-15 22:13:34 8 Comments

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

16 comments

@Phil Yu 2020-09-10 07:39:50

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

@Rajab Muhamed Rajab 2020-06-29 12:07:51

**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();

});

@Fabian Madurai 2019-01-29 19:11:31

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

@Pascal Tovohery 2019-01-24 08:15:10

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/

@Peter Bailey 2009-12-15 22:19:46

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="//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/

@Katrina 2015-05-20 16:50:42

It should be noted too, that the length is different between the two as well. jsfiddle.net/sUTVg/458

@Canis 2017-10-12 18:35:21

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

@Mustkeem K 2018-03-30 05:51:32

Well in simple term.

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

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

@Peter Krauss 2013-08-24 11:51:07

((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());

@Scott Simontis 2015-08-31 15:15:04

But if dealing with untrusted input, you should use text() whenever possible.

@Peter Krauss 2015-08-31 20:09:45

@ScottSimontis when you set nodeValue property, it transforms ">" into "&lt;", etc.

@Linh Dam 2016-04-08 18:19:12

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.

@Peter Krauss 2016-04-09 19:15:33

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.

@Octavioamu 2019-01-25 15:08:33

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

@Deb 2015-08-06 23:49:09

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.

@Minhaz 2016-04-12 15:36:36

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.

@david 2013-05-21 11:37:59

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

@MKaama 2017-08-19 08:54:51

Please correct your answer, the first snippet should use text().

@Adorjan Princz 2013-08-18 07:48:11

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.

@Owais Qureshi 2012-12-17 08:25:24

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

@Katie 2018-09-12 16:57:16

This answer was the easiest to understand and best formatted +1

@Gem 2019-05-09 09:39:14

What is the diff bw :: html(data); & val(data); @Owais Qureshi

@Michiel Kalkman 2009-12-15 22:23:54

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

@Seth 2009-12-15 22:23:50

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

@davidcl 2009-12-15 22:20:31

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.

@d512 2013-02-28 16:04:34

This should have been included in the selected answer to explain what is really going on.

@Andrew Hare 2009-12-15 22:17:52

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

@Brettk 2009-12-15 22:20:37

Sorry, I don't quite understand. Could you further explain. Thanks

@Brettk 2009-12-15 22:21:13

What do you mean the 2nd example will "encode"? It's already encoding, no?

@Andrew Hare 2009-12-15 22:22:29

@Brettk - I said "encode" but that was more a slip of the fingers. I changed my answer to better reflect what I mean.

@Mottie 2009-12-15 22:25:33

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.

Related Questions

Sponsored Content

19 Answered Questions

[SOLVED] Where should I put <script> tags in HTML markup?

66 Answered Questions

[SOLVED] How do I check whether a checkbox is checked in jQuery?

43 Answered Questions

[SOLVED] Is there an "exists" function for jQuery?

  • 2008-08-27 19:49:41
  • Jake McGraw
  • 774470 View
  • 2820 Score
  • 43 Answer
  • Tags:   javascript jquery

59 Answered Questions

[SOLVED] How do I check if an element is hidden in jQuery?

59 Answered Questions

[SOLVED] What is the best way to detect a mobile device?

5 Answered Questions

[SOLVED] What is the difference between properties and attributes in HTML?

41 Answered Questions

[SOLVED] Setting "checked" for a checkbox with jQuery

13 Answered Questions

[SOLVED] event.preventDefault() vs. return false

29 Answered Questions

[SOLVED] Get selected element's outer HTML

  • 2010-03-10 19:09:02
  • Ryan
  • 458308 View
  • 794 Score
  • 29 Answer
  • Tags:   jquery

Sponsored Content