JavaScript - innerText Property

The innerText property in JavaScript is used to get or set the text content of an element. Unlike innerHTML, which can return or set HTML content, innerText works only with the plain text of the element, ignoring any HTML tags inside the element.

Syntax

element.innerText = "new text";

In the syntax above, element refers to the DOM element whose text you want to change, and new text is the plain text content you want to set in the element.

Example of innerText Property

In this example, we change the text of a `

` element using the innerText property:

Example


<script type="text/javascript">
function changeText() {
    document.getElementById("demo").innerText = "This is the new text content!";
}
</script>
        
<div id="demo">This is the original text content.</div>        
<input type="button" onclick="changeText()" value="Change Text">

Output

When the "Change Text" button is clicked, the text content of the `
` element will change to "This is the new text content!".
This is the original text content.

Advanced Example: Using innerText to Toggle Text

In this advanced example, we use the innerText property to toggle the text of a paragraph between two values:

Example


<script type="text/javascript">
    function toggleText() {
        var textElement = document.getElementById("toggleText");
        if (textElement.innerText === "Hello, World!") 
    {
            textElement.innerText = "Goodbye, World!";
        } else {
            textElement.innerText = "Hello, World!";
        }
    }
</script>
        
<p id="toggleText">Hello, World!</p>
<input type="button" onclick="toggleText()" value="Toggle Text">                        ;

Output

When the "Toggle Text" button is clicked, the text content of the paragraph will toggle between "Hello, World!" and "Goodbye, World!".

Hello, World!