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 开发者_C百科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.
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.
.html(): Get the HTML contents of the first element in the set of matched elements.
.text(): Get the combined text contents of each element in the set of matched elements, including their descendants.
With .text() you get the real displayed text. With .html() you get the html of all childelements.
.html() gives you HTML content. If it were to transform <
and >
to opening and closing tags it could easily mess everything up by creating meaningless elements. i.e. <world>
element in your example
.text() gives you text content that does not have any Markup code in it. Therefore it is safe to transform <
and >
to "less than" and "greater than" signs.
精彩评论