[ Team LiB ] |
14.11 Creating Mixed Element and Text NodesNN 6, IE 5(Mac)/6(Win) 14.11.1 ProblemYou want to generate content that consists of elements as well as text inside those elements. 14.11.2 SolutionUse 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. 14.11.3 DiscussionTreat 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, but possible. Assembling mixed content, not as nodes but as strings, plays nicely in the innerHTML property of all elements (in IE 4 or later and NN 6 or later). The equivalent of the node approach just shown looks like the following: var newContent = "I am <em>very</em> happy to see you."; Then assign the new content to the innerHTML property of the desired element, which replaces the existing content with the new content. The IE-only DOM equips elements with another method that assists insertion of strings containing text with or without HTML markup that is to be treated as renderable HTML. The insertAdjacentHTML( ) method (compatible back to IE 4) lets you determine where the insertion goes in relation to the element. The method takes two parameters. The first is a case-insensitive string signifying the relative location of the insertion point for the new content. Here are the four possible values for the first parameter:
The new content is the second parameter. For example, to append the HTML string created earlier to an existing element whose ID is myP, the backward-compatible IE-only syntax is: document.all("myP").insertAdjacentHTML("BeforeEnd", newContent); Internet Explorer offers a large set of proprietary content manipulation methods, shown in Table 14-1.
14.11.4 See AlsoRecipe 14.9 for creating a new element; Recipe 14.10 for creating a new text node. |
[ Team LiB ] |