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
204,021 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