Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Interactive Web Pages with JavaScript Traversing and Manipulating the DOM with JavaScript Perform: Traversing Elements with querySelector

innerText vs innerHTML

As I was looking this up I came across someone saying innerText is not supported across all browsers and that it automatically decodes html? I'm thinking that it does not automatically decode html might be why we use it in this scenario (generating html form fields with js) although not being supported across all browsers has me curious.

2 Answers

Steven Parker
Steven Parker
231,248 Points

That may be old advice. According to Can I Use?, innerText is supported in all common browsers.

There's also another similar property named textContent. The choice of which to use should be based on function, since they do different things. For example, using this code:

<p id="test">    This element    contains <span>an inner span</span>. </p>

The values of these properties of the "test" paragraph will be:
innerText: "This element contains an inner span." :point_left: Just the text, trimmed and space-collapsed.
innerHtml: " This element     contains <span>an inner span</span>. " :point_left: All spacing and inner element tags.
textContent: " This element     contains an inner span. " :point_left: Spacing, but no tags.

Thanks Steve

Unlike innerText, though, innerHTML lets you work with HTML rich text and doesn't automatically encode and decode text. In other words, innerText retrieves and sets the content of the tag as plain text, whereas innerHTML retrieves and sets the same content but in HTML format.

Thank you Jacob