Whilst most JS coders are vaguely familiar with Element.appendChild and may have heard of Element.insertBefore, the possibilities using the various next/previous/child methods and how insertBefore targets a child element and not the Element of the method often eludes understanding...
... when really there are four possibilities that really opens doors to what you can do on the DOM.
Let's say we have this:
<div>
<div id="section">Section 1</div>
</div>
and:
var
section = document.getElementById('section'),
testTextNode = document.createTextNode(' HEY! ');
Let's say you want to insert testTextNode into section at the end of its text. That's easy.
section.appendChild(testTextNode);
That would give you the rought equivalent of:
<div>
<div id="section">Section 1 HEY! </div>
</div>
But what if you want it before? Well, that's where insertBefore comes into play... but the second paramenter of insertBefore is the trick, as you have to say WHAT to put it before. How about the firstChild?
section.insertBefore(testTextNode, section.firstChild);
Sure enough, you get roughly this:
<div>
<div id="section"> HEY! Section 1</div>
</div>
Neat, huh? Well let's dial it up a notch. How about inserting it BEFORE #section?
section.parentNode.insertBefore(testNtextNode, section);
... and we get:
<div>
HEY! <div id="section">Section 1</div>
</div>
as our result. We can also put it after.
section.parentNode.insertBefore(testTextNode, section.nextSibling);
Which gives us:
<div>
<div id="section">Section 1</div> HEY!
</div>
So to sum up:
// appendChild for last in targeted element
section.appendChild(testTextNode);
// insertBefore firstChild for first in target
section.insertBefore(testTextNode, section.firstChild);
// target.parentNode to target places before
section.parentNode.insertBefore(testTextNode, section);
// target.parentNode to target.nextSibling for after
section.parentNode.insertBefore(testTextNode, section.nextSibling);
Powerful simple techniques that I rarely see, and again where the power of the DOM really shines, as you can insert any DOM Node in this manner.