revision:
The createTextNode() method creates a new Text node. This method can be used to escape HTML characters.
All HTML elements are nodes. Elements, Attributes, and Texts are nodes. Some elements contain other nodes, text nodes, or attribute nodes.
document.createTextNode(data)
Parameters:
data : required. A string containing the data to be put in the text node.
const textNode = document.createTextNode("Hello World"); document.body.appendChild(textNode);
const h1 = document.createElement("h1"); const textNode = document.createTextNode("Hello World"); h1.appendChild(textNode);
const para = document.createElement("p"); const textNode = document.createTextNode("Hello World"); para.appendChild(textNode);
example: create text node
First line of paragraph.
<div> <button onclick="addTextNode('YES! ');">YES!</button> <button onclick="addTextNode('NO! ');">NO!</button> <button onclick="addTextNode('WE CAN! ');">WE CAN!</button> <br> <p id="p1">First line of paragraph.</p> </div> <script> function addTextNode(text) { const newtext = document.createTextNode(text); const p1 = document.getElementById("p1"); p1.appendChild(newtext); } </script>
example: create a <h4> element and <p> element with a text node
<div> <p id="text-1"></p> <p id="text-2"></p> </div> <script> const h4 = document.createElement("h4"); const textNode = document.createTextNode("this is a h4 element: Hello World"); h4.appendChild(textNode); document.getElementById("text-1").appendChild(h4); const p1 = document.createElement("p"); const textNode1 = document.createTextNode("this is a p element: Hello World"); p1.appendChild(textNode1); document.getElementById("text-2").appendChild(p1); </script>
example: click the button to create a <p> element with some text
<div> <button onclick="createText()">create text</button> <p id="text-3"></p> </div> <script> function createText() { var x = document.createElement("P"); var p = document.createTextNode("This is a sample paragraph created with createTextNode()"); x.appendChild(p); document.getElementById("text-3").appendChild(x); } </script>