Given the following HTML fragment:
<p id="para">hello <world></p>
The jQuery .text()
and .html()
methods will return different values...
var text = $('#para').text(); // gives 'hello <world>'
var html = $('#para').html(); // gives 'hello <world>'
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 <
and >
doesn't seem to be documented anywhere.
Can anyone comment on the rationale for this difference?
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.
text() – This method sets or returns the text content of elements selected. html() – This method sets or returns the content of elements selected.
So you need to escape <, or & when followed by anything that could begin a character reference. Also The rule on ampersands is the only such rule for quoted attributes, as the matching quotation mark is the only thing that will terminate one.
< stands for lesser than (<) symbol and, the > sign stands for greater than (>) symbol .
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 <world>
I think it happens so that round-tripping can work correctly. You should be able to get a perfect clone of the original content by calling $() on the result of html():
var clonedContent = $($("#para").html());
If HTML entities were not escaped by html()
, the above would create a <world>
element that doesn't exist in the original content.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With