JavaScript textContent Property Tutorial

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

What is Element textContent Property in JavaScript?

The JavaScript Element textContent property is used to get the entire text content of an element and the entire text content of all its descendants.

Remember that we’re saying the entire text content! For example, if the target element is the <style>, even though the content of this element won’t render on the page, still we get the content if the textContent property was called on such element.

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

If we assign a value to the textContent 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 only the text content of an element and its descendants that are rendered on a page, you can use the innerText property for that matter. Also using this property, we can’t get those text-content that are hidden on a page using CSS.

JavaScript textContent Property Syntax:

element.textContent;

element.textContent = “newValue”;

JavaScript textContent Property Input Value

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

JavaScript textContent Property Return Value

The return value of this property is the text-content of the target element as well as the text content of all its descendants (if any).

Example: JavaScript change text

See the Pen JavaScript change text by Omid Dehghan (@odchan1) on CodePen.

How does the element textContent property work in JavaScript?

Note that the value we’ve set for the textContent 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 textContent 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).

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies