The HTML DOM createTextNode() method is used to create a Text Node with the specified text.
Example
Let us look at an example for the createTextNode() method −
<!DOCTYPE html>
<html>
<body>
<h2>createTextNode() example</h2>
<p>Click the below button to create a p element with some text.</p>
<button onclick="createText()">CREATE</button>
<script>
function createText() {
var x = document.createElement("P");
var p = document.createTextNode("This is a sample paragraph created with
createTextNode()");
x.appendChild(p);
document.body.appendChild(x);
}
</script>
</body>
</html>Output
This will produce the following output −

On clicking the CREATE button −

In the above example −
We have created a button CREATE that will execute the createText() function on being clicked by the user −
<button onclick="createText()">CREATE</button>
The createText() method creates the <p> element by using the createElement() method of the document object and assigns it to the variable x. We then create a text node using createTextNode() with some text and assigns it to the variable p.
We then append the text node to the <p> element using the appendChild() method. Finally the <p> element along with the text node are appended to document using the document.body appendChild() method:
function createText() {
var x = document.createElement("P");
var p = document.createTextNode("This is a sample paragraph created with createTextNode()");
x.appendChild(p);
document.body.appendChild(x);
}