Often, developers tend to render content dynamically on their web pages as the user interacts with their websites. This dynamic rendering makes the web page elegant while simultaneously encouraging user interactions. Javascript has an innerText
property that helps developers achieve this efficiently.
This innerText
property retrieves or sets the text content inside an HTML element and its descendants. This property is quite similar to the innerHTML
property of JavaScript, but there are some subtle differences between them.
Note: Please refer to this link to read more on the
innerHTML
property.
The primary difference between the two is that the innerText
property fetches or sets the textual content, whereas the innerHTML
property returns the HTML content of an element or all its descendants.
Now we have a basic understanding of the innerText
let's see the syntax for this property.
//Retrieve the innerText using the following syntax
element.innerText;
//Set the innerText using the syntax below
element.innerText = text
Note: Whenever we set the
innerText
property for an HTML element, the child nodes of the element are replaced by only one new text node.
The return value for the innerText
property is the text content of the HTML elements or all its descendants.
Note: The text content wrapped in
<script>
&<style>
tags is not returned using this property.
Let us now understand how can we retrieve the text content of an HTML element using innerText
with the help of a code example below:
The explanation for the code in the HTML tab is as follows:
<div>
which encloses the following elements:<img>
tag to render the educative logo, as seen in the output tab above.<div>
which encapsulates a child element in the form of <strong>
tag, which boldens the text. We use the innerText
property to fetch the <div>
text.<button>
element that fires the getTextContent()
method and listens to the onclick
event.<script>
tags to encapsulate JavaScript code and contain our getTextContent()
method. The description of the function is the following:document.getElementById()
method to get hold of the <div>
present on line 7.innerText
property provided and then display the text content using a Javascript alert
.The second primary use of this property is to set the innerText
of an HTML element, and the following code example illustrates the use:
The description for the code that resides in the HTML file is as follows:
<div>
now does not contain the <strong>
tags, so the text content does not appear bold.<button>
element now triggers the setTextContent()
method, primarily for setting the text content as the user clicks.setTextContent()
function that is explained below:<div>
, similar to what we have done in code example 1.innerText
property to manipulate the text content inside the target, <div>
, and assign it to a string
that we want to set the text content to as the user clicks on the <button>
.Note: To learn more on the
document.getElementById()
method, please visit this link.