The Document Object Model (DOM), Part 5: The createElement Method | 2
The Document Object Model (DOM), Part 5 (3)
The createTextNode
Method
The createTextNode
method is very similar to the createElement
method. Use the createTextNode
method to create text nodes. Use the createElement
method to create HTML tag nodes. The created text node is a stand-alone element under the document
object. This element is a single node that has neither children nor father, and is not related to any other existing document nodes. The only information attached to such a node is its string value. This string is the only parameter you need to specify when calling the createTextNode
:
newObject = document.createTextNode("This is an example string");
Let's prepare the text nodes for our table from Column 40. We need to prepare six nodes for the 3x2 table:
row1cell1Obj = document.createTextNode("This is row 1, cell 1");
row1cell2Obj = document.createTextNode("This is row 1, cell 2");
row2cell1Obj = document.createTextNode("This is row 2, cell 1");
row2cell2Obj = document.createTextNode("This is row 2, cell 2");
row3cell1Obj = document.createTextNode("This is row 3, cell 1");
row3cell2Obj = document.createTextNode("This is row 3, cell 2");
Notice that a new text node has neither children nor father. It is just a document "satellite" waiting to be adopted by a father or waiting to acquire some children. The following script demonstrates this node behavior after creation:
<HTML>
<HEAD>
<TITLE> DOM Demo </TITLE>
</HEAD>
<BODY ID="bodyNode">
<SCRIPT LANGUAGE="JavaScript">
<!--
row1cell1Obj = document.createTextNode("This is row 1, cell 1");
row1cell2Obj = document.createTextNode("This is row 1, cell 2");
row2cell1Obj = document.createTextNode("This is row 2, cell 1");
row2cell2Obj = document.createTextNode("This is row 2, cell 2");
row3cell1Obj = document.createTextNode("This is row 3, cell 1");
row3cell2Obj = document.createTextNode("This is row 3, cell 2");
alert(
"row1cell1Obj.firstChild = " + row1cell1Obj.firstChild + "\n" +
"row1cell1Obj.nodeName = " + row1cell1Obj.nodeName
);
// -->
</SCRIPT>
</BODY>
</HTML>
Run this script now. See that the new text node does not have any children. Also, notice that the returned value from the createTextNode is indeed an object.
Produced by Yehuda Shiran and Tomer Shiran
Created: July 19, 1999
Revised: July 19, 1999
URL: https://www.webreference.com/js/column44/createtext.html