javascript
  1. javascript-innertext-property

JavaScript innerText Property

The innerText property is a part of the Document Object Model (DOM) in JavaScript. It is used to set or retrieve the text content of an element in an HTML document. In simpler words, it is used to access or modify the text content of an HTML element.

Syntax

The syntax for using the innerText property in JavaScript is:

element.innerText = text;

Here, element is the HTML element whose text content is to be accessed or modified, and text is the new text content of the element.

Example

Let's consider an example of a paragraph element with an id of demo.

<p id="demo">This is a paragraph</p>

To modify its text content using the innerText property in JavaScript, we can use the following code:

var para = document.getElementById("demo");
para.innerText = "This is a new paragraph";

Output

The output of the above JavaScript code will be a paragraph element with the updated text content:

<p id="demo">This is a new paragraph</p>

Explanation

The innerText property is used to modify the text content of an HTML element. In the example above, we first accessed the paragraph element using the getElementById() method and stored it in a variable named para. We then used the innerText property to modify its text content to "This is a new paragraph".

Use

The innerText property can be used in various ways to manipulate the text content of HTML elements. Some common use cases include:

  • Changing the text content of a heading or paragraph element dynamically based on user input or other events.
  • Updating the text content of a button or link element to provide feedback to the user.
  • Retrieving the text content of an element for further processing or validation.

Important Points

Here are a few important points to keep in mind while using the innerText property:

  • The innerText property is case-sensitive, i.e., the text content should be provided as it appears in the HTML document.
  • The innerText property returns only the visible text content of an element, excluding any HTML tags or attributes.
  • The innerText property is not supported in older versions of Internet Explorer. In such cases, the textContent property can be used as a fallback.

Summary

In summary, the innerText property is used to access or modify the text content of an HTML element in JavaScript. It provides a simple and efficient way to manipulate the text content of elements dynamically based on user input or other events. However, it should be used with caution as it can affect the accessibility and SEO of the web page.

Published on: