tags:

views:

549

answers:

3

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?

+5  A: 

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);
Paolo Bergantino
I like your solution. :)
James Black
+1  A: 

If the user can give an id of an element that will be where the iframe should be, then it would be possible to just use css to move the iframe to where it should be on the page.

James Black
A: 

Paulo's answer can also be done without the ID, by simply looking for the last <script> element. This must be the script block we're in, because JavaScript guarantees all content past the closing tag of the current script block has not yet been parsed(*):

 var scripts= document.getElementsByTagName('script');
 var script= scripts[scripts.length-1];
 script.parentNode.insertBefore(d, script);

This can be put in an onload/ready function if you like, but if so the ‘var script’ must be calculated at include-time and not in the ready function (when that executes, more <script>s will have been parsed).

(*: except in the case of <script defer>.)

bobince