This post will explain the below-listed aspects regarding the textContent property:
- What is textContent in JavaScript
- Basic Syntax
- What does textContent property Return
- How to Use textContent in JavaScript
So, let’s start!
What is textContent in JavaScript
It is a property that allows us to get or set the text content of a node, or an element. Setting the textContent property will remove and replace the child nodes with the new text node.
Basic Syntax
The below-given snippet will show how to get/return the text content of a node or element:
Let’s consider the below snippet to understand how to set the text content of a node or element:
What does textContent property Return
In JavaScript, the textContent property returns the content of an element/node and all of its descendents(child nodes). It returns null if the element/node is a document/notation type.
How to Use textContent property in JavaScript
Up till now, we are done with the theoretical part of the textContent property. Now, let’s move one step ahead to implement all these theoretical concepts practically.
Example1: Let’s consider the below-given code to understand how to get/return the text content of an element using the textContent property in JavaScript:
<body>
<h2> id="greetings">Welcome to linuxhint.com</h2>
</body
<script type="text/javascript">
let content = document.getElementById('greetings');
alert(content.textContent);
</script>
</html>
In the above code snippet, firstly, we utilized the getElementById() to select the h2 element with the id ‘greetings’. Afterward, we accessed the textContent property to display the text of the node.
This is how the textContent property modifies the text of an element in JavaScript.
Example2: How to set the textual content of an element using textContent property:
<body>
<h3>textContent Property</h3>
<p id="change" onclick="clickMe()">CLICK ME</p>
<script>
function clickMe() {
document.getElementById("change").textContent = "Welcome to linuxhint.com";
}
</script>
</body>
</html>
The above code block will produce the following output:
This is how the textContent property sets the text in JavaScript.
Conclusion
In JavaScript, the textContent property allows us to get or set the text content of a node, or an element. Setting the textContent property will remove and replace the child nodes with the new text node. The textContent property returns the content of an element/node and all of its descendents(child nodes). It returns null if the element/node is a document/notation/document type. This write-up explained what textContent is, what it returns, and how to use it in JavaScript.