TJKDesign: Home Page
Creative Commons License
This work is licensed under a
Creative Commons License.

If you've found this beneficial, consider making a donation through Paypal

Guild of Accessible Web Designers Logo
Valid XHTML 1.0!
Section 508
Web Standards
Tables-less Layout
Frames: a solution or a problem?
XML Feed
NN4.7 Safe!

divaHTML logo
Bookmark this article at these sites:

Using DOM methods rather than innerHTML to wrap all children of a node into a new element.

innerHTML is a very handy property that can be used to do many things; like wrapping the content of an element inside another one for example.
So this:

document.getElementById('heading').innerHTML='<span>'+document.getElementById('heading').innerHTML+'</span>'

Would transform this:

<h1 id="heading">This is a <em>Title</em></h1>

Into this:

<h1 id="heading"><span>This is a <em>Title</em></span></h1>

Unfortunately, innerHTML is a proprietary property and it is said that it should be avoided at all cost (or atleast for many reasons). The problem with this advice is that it doesn't really come with a solution and until now I had been able to find out a simple way (using only DOM methods) to do what innerHTML does so easily.

I say until today because I think I found a solution (at least for elements containing not too many nodes since we're moving every single child node at a time rather than moving a "whole branch of the tree").

This is it:

<!--
function TJK_moveNodes(sourceNode,targetNode,newWrapperTagName){// v1.0 Copyright (c) 2006 TJKDesign - Thierry Koblentz
  if (!document.createElement) return;
  var nodeRecipient=(targetNode)?targetNode:document.createElement(newWrapperTagName);
  while(sourceNode.childNodes.length)nodeRecipient.appendChild(sourceNode.childNodes[0]);	
  if(newWrapperTagName)sourceNode.appendChild(nodeRecipient);
}
//-->

This function does two things depending on which of the two last parameters is used:

  • If targetNode is used, all nodes from an element (sourceNode) are moved into another (targetNode).
  • If newWrapperTag is used, all the nodes inside an element (every child node in sourceNode) are wrapped inside a new element (newWrapperTag).

Take a look at this code in action.

If this is nothing new, if somebody came up with this already then I can say that Google does not know yet. Because I believe I looked everywhere for a simple solution like this one.

Please use this contact form to send feedback and report errors.