How can I append a new element in place in JavaScript?

dom, javascript

Solution

Mm. You could do:

document.write("<div id='iframecontainer'></div>");
document.getElementById('iframecontainer').innerHTML = '...';

But that feels ugly/wrong in a lot of different levels. I am not aware of any other alternatives, though.

EDIT: Actually, a quick google search revealed this artlcle which discusses why `document.write` is ugly and a nice alternative for the particular pickle you're in: Give your `script` tag an ID!

<script id="iframeinserter" src=".."></script>

And then you can get a reference to the script tag and insert the iframe before it:

var newcontent = document.createElement('iframe'); 
var scr = document.getElementById('iframeinserter'); 
scr.parentNode.insertBefore(newcontent, scr); 

Problem

I've created a JavaScript script that can be pasted on someone's page to create an iFrame. I would like for the person to be able to paste the script where they would like the iFrame to appear. However, I can't figure out how to append the DOM created iFrame to the location where the script has been pasted. It always appends it to the very bottom of the body. How do I append in place?

Original source