myDocument.createTextNode( [ data ] ) in DOM Level 2 Core

Create a new Text node, with optional content.

Arguments

nametypedescription
data String [optional] The string contents of the tex
Return Type
Text

Description

The following examples show two ways to use this method in a context where document exists as a reference to a dom::Document object:

var p1 = document.getElementById('firstParagraph');
var p2 = document.getElementById('secondParagraph');

var t1 = document.createTextNode("Hello World");
p1.appendChild(t1);

var t2 = document.createTextNode();
p2.appendChild(t2);
t2.nodeValue="How's it going?";

And just to show that DOM programming doesn't have to increase your line count dramatically vs. various UA-specific methods:


//if the paragraph doesn't already have a Text node:
document.getElementById('firstParagraph').appendChild(document.createTextNode('Hello World'));

//if it already has a Text node you want to change:
document.getElementById('firstParagraph').firstChild.nodeValue='Hello World';

Note: the return type is a dom::Text node object, and not a string value as "Text" might imply.