What Is A Text Node, Its Uses? //document.createTextNode()

All viewable HTML text in a page (except text in form elements or custom embedded objects) is in text nodes. The page consists of a number of different types of nodes (you can see a listing of the different node types here: https://developer.mozilla.org/en-US/docs/Web/API/Node.nodeType), some of which can have child nodes and some of which cannot. For example, a div is an ELEMENT node which can contain child nodes. Those child nodes can be other ELEMENT nodes or they can be TEXT nodes or COMMENT nodes or other types of nodes.

When you set the .innerHTML property of an element node, it creates the appropriate nodes and makes them child nodes of the element that you set the innerHTML property on. If there is text in the innerHTML you set, then text nodes will be created to hold it.

DOCUMENT_NODE, ELEMENT_NODE and TEXT_NODE are the most common node types and are in every page that has text.

In your code example:

var div = document.createElement('div');
var text = document.createTextNode('Y HALO THAR');
div.appendChild(text);

This creates one text node and puts it into the div you created. It generates the same DOM structure as this:

var div = document.createElement('div');
div.innerHTML = 'Y HALO THAR';

In the latter case, the system creates the text node for you.


In plain javascript programming (jQuery tends to shield developers from nodes that aren’t of type ELEMENT_NODE), you will encounter text nodes any time you walk the child nodes of an element that has text in it. You will need to check the .nodeType of each child to know whether it is another element or a text node or some other type of node.


In general, there aren’t a lot of reasons to manipulate text nodes directly as you can often use the higher level .innerHTML property more simply. But, to give you an idea, here are a couple reasons you might want to deal directly with text nodes:

  1. You want to change some text without affecting any of the elements around it. .innerHTML creates all new elements for the affected elements which kills any event handlers which might have been set on them, but setting the .nodeValue on a text node doesn’t cause any elements to get recreated.

  2. If you want to find just the text in a document without any of the resulting HTML markup and know exactly where each piece of text is in the DOM hieararchy, you can just search for all the text nodes. For example, if you were doing a text search of the document and then highlighting found text, you would probably search text nodes directly.

  3. You want to display some text without any security risks that it might contain other markup that the browser would parse and interpret if you used .innerHTML. So, you create a text node and set the value of its text and the browser won’t interpet any HTML in it. Modern browsers can also use the .textContent property of an element instead of .innerHTML to solve this problem too.

Leave a Comment