Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
634 views
in Technique[技术] by (71.8m points)

jquery - Differences between .text() and .html() with escaped < and > characters

Given the following HTML fragment:

<p id="para">hello &lt;world&gt;</p>

The jQuery .text() and .html() methods will return different values...

var text = $('#para').text(); // gives 'hello <world>'
var html = $('#para').html(); // gives 'hello &lt;world&gt;'

The jQuery documentation states

The result of the .text() method is a string containing the combined text of all matched elements.

and...

In an HTML document, we can use .html() to get the contents of any element. If the selector expression matches more than one element, only the first one's HTML content is returned.

But this specific difference with &lt; and &gt; doesn't seem to be documented anywhere.

Can anyone comment on the rationale for this difference?

Edit

A little more investigation suggests that the values .text() and .html() match those from the native JavaScript innerText and innerHTML calls respectively (when the jQuery selector has returned a single element, at least). Again, this is not reflected in the jQuery documentation so I am not 100% sure if this observation holds true in all scenarios. Reading through the jQuery source reveals that this isn't what's actually going on under the hood.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is in accordance with the corresponding JavaScript methods textContent and innerHTML.

>> console.log(document.getElementsByTagName('p')[0].textContent);
hello <world>

>> console.log(document.getElementsByTagName('p')[0].innerHTML);
hello &lt;world&gt;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...