views:

516

answers:

2

Hi all:

I was wondering whats the difference between innerText and html()?

Thanks.

+14  A: 

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.

Chris Pebble
Does the fact that `innerText` is an IE only property and has nothing to do with jQuery mean anything? :)
Doug Neiner
Great examples Chris. +1
Doug Neiner
Very good point dcneiner, updated post to reflect that :).
Chris Pebble
+7  A: 

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 &lt;a&gt;Hi&lt;/a&gt;
Doug Neiner