I am trying to get javascript which adds iframe by Javascript. It create iframe before tag.
You can see jsfiddle demo. But I dont want to add tag. I just want to add external .js file which do all things on its own!
I am trying to get javascript which adds iframe by Javascript. It create iframe before tag.
You can see jsfiddle demo. But I dont want to add tag. I just want to add external .js file which do all things on its own!
Use this
var newElem = createElement('script');
newElem.setAttribute('src', 'http://example.com/js/script.js');
newElem.setAttribute('type', 'text/javascript');
newElem.setAttribute('language', 'JavaScript');
document.getElementById('IdFromTheHeadElem').appendChild(newElem);
You can create the tag with
document.write("<iframe..............>");
Edit: The solution i wrote in the comments in jQuery:
In your JS file:
$(function(){
$('#container').html('<iframe........');
});
In your HTML:
<div id="#container"></div>
Include it in your header with:
<script src=".............yourscriptname.js"></script>
From your jsfiddle it looks like you should be doing this (in plain JS) to avoid defining iframe directly in the HTML code:
var iframe = document.createElement('iframe');
iframe.id = 'iframeID';
document.body.appendChild(iframe);
// the rest is manipulating this iframe
iframe.contentDocument.write("<html><head></head><body><div id='foo'>The div</div></body></html>");
iframe.contentDocument.getElementById('foo').innerHTML = "Greetings from outside!";
code on jsfiddle (I wrapped the code there in a closure to prevent polluting the global namespace)
The document.body.appendChild(iframe); should be changed to something else depending where you want to place it inside the page (e.g. document.getElementById('some-div-id').appendChild(iframe);)