JavaScript innerText Property Tutorial

In this section, we will learn what the Element innerText property is and how to use it in JavaScript.

What is Element innerText Property in JavaScript?

The JavaScript Element innerText property is used to get the “rendered” text content of an element and the rendered text content of all its descendants.

Remember that we’re saying the “rendered” text content! For example, if the target element is the <style>, no content of this element will be returned if we call this property on such an element! This is because the element’s content won’t render on a page.

But for a <p> element, for example, if we call this property, its text content will return as a result.

Also, using the innerText property, you can’t get those text-content that are hidden using CSS.

If we assign a value to the innerText property, it will replace the old content of the target element (including the entire descendants) with this new value.

Note: if you want to get the text content of an element and its descendants no-matter if they are rendered on the page or not, you can use the textContent property for that matter. Also using this property, we can get those text-content that are hidden on a page using CSS.

Element innerText Property Syntax:

element.innerText;

element.innerText = “newValue”;

Element innerText Property Input Value

The value we assign to the innerText property is a string value that will replace the old value of the target element.

Element innerText Property Return Value

The return value of this property is the rendered text-content of the target element, as well as the text content of all its descendants.

Example: JavaScript set innerText

See the Pen JavaScript set innerText by Omid Dehghan (@odchan1) on CodePen.

How does Element innerText property work in JavaScript?

Note that the value we’ve set for the innerText property contains the <p> element as well!

But when this value rendered on the page, we see the <p> element itself instead of its affect!

This is because using the innerText property, any text content will appear as just a rendered text and browsers won’t consider any word of that content as special HTML, CSS, or JavaScript keyword.

Note: use the innerHTML property if you want browsers to interpret the special keywords in text content we assign to an element as well. (Like the <p> element we’ve put in the text content of the last example).

Leave a Reply