Adding stuff to the page ...and getting an immediate reference to the thing you added so you can keep working with it

This won't look like too much...but something does actually happen here.

navigate my process

related content

The Explanation

Part 1 was all fine and dandy for basic scenarios. What's more interesting, and surprisingly complex, is when you need to put something new into the document, and then immediately get a reference to it, because you want to manipulate it, for whatever reason.

Again, here, I started thinking about the more hands-on document.createElement() method, above (which, note to self, I should go ahead and document for myself, at some point), but I got to wondering if there wasn't some way to still use the string syntax from above. After a little searching I was brought back to this DWB postabout using Range objects to and their createContextualFragment() method.

According to MDN, ranges are "a fragment of a document that can contain nodes and parts of text nodes." It feels a bit weird and obscure to me, though they've been in browsers basically forever now. Maybe it's that lack of IE 6-8 support that threw a blanket over it, to my mind.

Essentially what we're doing here, as I document in this example, is create a range object, then add a contextual fragment to it, which takes our HTML string as an argument. The trick here is that if you add the document fragment (or range) directly to the document, you lose your reference to the element—so you need to take the first child of the range, add that to the document using appendChild(), and store the return value in a variable so you can do stuff with it.