(I’m making notes here so I can find these techniques again later.)

I wanted to use JavaScript (W3C DOM compliant) to wrap the content of a heading with an a element, ie.

<h3>This is <em>my</em> header</h3>

Needed to become

<h3><a href=”#mytarget”>This is <em>my</em> header</a></h3>

Here’s what I came up with:

var h = document.getElementBySomeMethod('h3'); // grab the heading
var a = document.createElement('a');       // create an a element
    a.setAttribute('href', '#mytarget');   // set the href
while (h.childNodes.length > 0) {          // for each child node in the h3
    a.appendChild( content.firstChild );   // move the node to the a element
    }
h.appendChild(anchor);                    // stick a under the now empty h3

It seems so simple now to look at. Took me ages to figure it out. :(