Reputation: 2347
What's the the difference between innerText
, text()
, and html()
?
Upvotes: 10
Views: 13165
Reputation: 37587
innerText
(or text()
if you're using jQuery) doesn't include any HTML tags. So if you had a div that contained:
View my <a href="profile.html">profile</a>
innerText
/ text()
would return
View my profile
while html()
would return
View my <a href="profile.html">profile</a>
As dcneiner points out html()
/text()
are jQuery properties (and supported across browsers) while innerText is not implemented by all browsers (although it works in the most recent versions of IE, Safari, and Chrome).
Basically you'll want to use text()
isntead of innerText whenever possible. See dcneiner's post (or the jQuery docs) for some other things that make text()
awesome.
Upvotes: 29
Reputation: 66221
The difference is that innerText
is an IE only property on a DOM object and html()
is a function of the jQuery object.
However, if you were comparing text()
and html()
then the difference is that text()
strips all HTML from the contents of an element before returning and html()
includes includes the HTML.
Additionally, text()
will return the text of all matched elements and concatenate them together:
<span>Hi, </span><span>how are </span><span>you?</span>
$("span").text(); // returns: Hi, how are you?
But html()
will only return the first matched items innerHTML
property:
$("span").html(); // returns: Hi,
One last cool thing, is that .text()
auto escapes all HTML:
$("span:first").text('<a>Hi</a>'); // writes <a>Hi</a>
Upvotes: 11