ChatGPT解决这个技术问题 Extra ChatGPT

What is the difference between jQuery: text() and html() ?

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

W
WizKaleeb

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('Linkhello'); $("#div2").text('Linkhello'); });

http://jsfiddle.net/hossain/sUTVg/


It should be noted too, that the length is different between the two as well. jsfiddle.net/sUTVg/458
@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.
7
7 revs, 4 users 77%

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

But if dealing with untrusted input, you should use text() whenever possible.
@ScottSimontis when you set nodeValue property, it transforms ">" into "&lt;", etc.
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.
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.
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
A
Andrew Hare

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


Sorry, I don't quite understand. Could you further explain. Thanks
What do you mean the 2nd example will "encode"? It's already encoding, no?
@Brettk - I said "encode" but that was more a slip of the fingers. I changed my answer to better reflect what I mean.
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.
d
davidcl

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.


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

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.

.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


This answer was the easiest to understand and best formatted +1
What is the diff bw :: html(data); & val(data); @Owais Qureshi
N
Nisse Engström

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.


A
Adorjan Princz

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.


P
Paul Roub

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


S
Seth

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

M
Michiel Kalkman

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


M
Mustkeem K

Well in simple term.

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

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


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).
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.
P
Pascal Tovohery

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/


B
BenMorel

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


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

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.


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

});

R
Rohit

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


D
Deepak Rai
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