Flat Preloader Icon

JS innerText Property

The innerText property in JavaScript is used to get or set the text content of an element, excluding any HTML tags. It represents only the visible text within an element, without considering the HTML structure or any child elements.

Getting Text Content:

  • To retrieve the text content of an element, you can simply access its innerText property. It returns a string representing the visible text content of the element, excluding any HTML tags.
				
					let element = document.getElementById("example");
let textContent = element.innerText;
console.log(textContent);

				
			

Setting Text Content:

  • To set the text content of an element, you can assign a string containing plain text to its innerText property. This will replace the existing text content of the element with the new text.
				
					let element = document.getElementById("example");
element.innerText = "New text content";

				
			

Example Usage:

				
					<!DOCTYPE html>
<html>
<head>
    <title>innerText Property Example</title>
</head>
<body>
    <div id="example">
        Initial text content
    </div>

    <button onclick="changeContent()">
        Change Content</button>

    <script>
        function changeContent() {
let element = document.getElementById
("example");element.innerText 
= "New text content";
        }
    </script>
</body>
</html>

				
			

Note:

  • Unlike innerHTML, which deals with HTML content including tags, innerText deals only with the visible text content of an element.
  • When setting innerText, any existing HTML content within the element will be replaced by the new text content.
  • innerText returns the visible text as it appears on the rendered page, which may differ from the raw text content in the HTML source if CSS styles or JavaScript modifications affect the display.

Compatibility:

  • The innerText property is supported in all modern browsers, including Chrome, Firefox, Safari, Edge, and Internet Explorer (IE9+).
  •