The textContent property in HTML is used to set or return the text content of the specified node and all its descendants. This property is very similar to nodeValue property but this property returns the text of all child nodes.
Syntax
- It is used to set the text of node.
node.textContent = text- It is used to return the text of node.
node.textContentProperty Value: It contains single value text which contains node the node content.
Return Value: It returns a string value which represents the text content of a particular node node and all descendants.
Example 1:
<!--Driver Code Starts-->
<!DOCTYPE html>
<html>
<head>
<title>
HTML DOM textContent Property
</title>
</head>
<body>
<h1>GeeksforGeeks</h1>
<h2>HTML DOM textContent Property</h2>
<!--Driver Code Ends-->
<button id = "geeks" onclick = "MyGeeks()">
Submit
</button>
<p id = "sudo"></p>
<script>
function MyGeeks() {
var text =
document.getElementById("geeks").textContent;
document.getElementById("sudo").innerHTML = text;
}
</script>
<!--Driver Code Starts-->
</body>
</html>
<!--Driver Code Ends-->
Example 2:
<!--Driver Code Starts-->
<!DOCTYPE html>
<html>
<head>
<title>
HTML DOM textContent Property
</title>
</head>
<body>
<h1>GeeksforGeeks</h1>
<h2>HTML DOM textContent Property</h2>
<!--Driver Code Ends-->
<p id = "geeks" onclick = "MyGeeks()">
Hello Geeks!
</p>
<script>
function MyGeeks() {
document.getElementById("geeks").textContent
= "Welcome to GeeksforGeeks!";
}
</script>
<!--Driver Code Starts-->
</body>
</html>
<!--Driver Code Ends-->
- It returns the concatenated text of the node and all its descendants (excluding comments and processing instructions). Setting it removes all child nodes and replaces them with a single text node containing the new value.
- It differs significantly from innerText. textContent includes text from all elements (including <script> and <style>), is not affected by CSS styling or visibility, and does not trigger a reflow. innerText only returns “human-readable” text and respects CSS.