O'Reilly logo

JavaScript & DHTML Cookbook by Danny Goodman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Creating Mixed Element and Text Nodes

NN 6, IE 5(Mac)/6(Win)

Problem

You want to generate content that consists of elements as well as text inside those elements.

Solution

Use the W3C DOM DocumentFragment object as an arbitrary container while assembling the content:

var frag, myEm, txt1, txt2;
frag = document.createDocumentFragment( );
myEm = document.createElement("em");
txt1 = document.createTextNode("very");
myEm .appendChild(txt1);
txt1 = document.createTextNode("I am ");
txt2 = document.createTextNode(" happy to see you.");
frag.appendChild(txt1);
frag.appendChild(myEm);
frag.appendChild(txt2);

At this point, the fragment (which starts and ends with text nodes) is ready for insertion or replacement at any existing element node in the document tree.

Discussion

Treat the DocumentFragment object like a scratch pad capable of containing any well-formed sequence of node types. The fragment exists solely in memory and is not a part of the document tree.

Internet Explorer implements the DocumentFragment object in Version 5 for the Macintosh and Version 6 or later for Windows. For earlier versions of Internet Explorer, there is no node-related equivalent. You can simulate the document fragment in memory by assembling element and text nodes in any generic container (such as a div or span). When it's time to place the content into the document tree, you can remove each child node of the temporary container, and append the removed node into the document's destination element. This is ugly, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required