0

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!

2
  • you do not want <iframe> tag in your code? Commented Apr 18, 2013 at 7:42
  • I dont want to add anything like <div> in html file I would just add <link .... >of js file Commented Apr 18, 2013 at 7:45

3 Answers 3

1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

how would it end up before </body> tag??
of course it will be end bevor the elements there you added ends
0

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>

2 Comments

I would add javascript file link in head... as i said in comment of my question
If you load the file into your header you have to wait until the dom is loaded (dom ready event) and select a item which should contain the iframe (a empty div for example) with "getElementById" then you can set the html source in this eleme nt with "innerHTML". I suggest you to use a library like jQuery because especially the dom ready event is difficult to implement in plain javascript (browser compatibility). If you want to avoid the dom ready event you have to write a function coll into your html source at the position the code should appear.
0

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);)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.