HTML - DOM Document createTextNode() Method



HTML DOM doument createTextNode() method is used to create a text node with the specified text.

Syntax

document.createTextNode(text);

Parameter

This method accepts a single parameter as listed below.

Parameter Description
text It represents the text which you want to add in the document.

Return Value

It returns the created text node.

Examples of HTML DOM Document 'createTextNode()' Method

The following examples illustrates use of createTextNode() method.

Create a Text Node

In the following example we have created a text node and appended to the body.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        HTML DOM document createTextNode() Method
    </title>
</head>
<body>
    <h3>HTML DOM document createTextNode() Method</h3>
    <button onclick="fun()">Create Text Node</button>
    <script>
       function fun() {
        let x = document.createTextNode("A simple text node is created..");
        document.body.appendChild(x);
       }
    </script>
</body>
</html>

Create a Paragraph Element

In the following example we have created a text node and appended to the body.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        HTML DOM document createTextNode() Method
    </title>
</head>
<body>
    <h3>HTML DOM document createTextNode() Method</h3>
    <button onclick="fun()">Create Text Node</button>
    <script>
       function fun() {
        let h=document.createElement("h1");
        let x = document.createTextNode("A simple text node is created..");
        h.appendChild(x);
        document.body.appendChild(h);
       }
    </script>
</body>
</html>

Supported Browsers

Method Chrome Edge Firefox Safari Opera
createTextNode() Yes 1 Yes 12 Yes 1 Yes 1 Yes 7
html_dom.htm
Advertisements