Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding IFRAME to DOM by Javascript

I want to add an iframe to the page. This iframe should refer to a URL. I added the below code to page HTML, but it doesn't work:

document.createElement('<iframe src='http://example.com'></iframe>');
like image 208
Xaqron Avatar asked Jun 12 '11 01:06

Xaqron


People also ask

Can JavaScript access an iframe?

In this article. Apart from accessing an element by adding its control to the Controls Repository, there is also the possibility to access an element within a web page's iframe via Javascript.

How do I add an iframe to my body?

createElement('iframe') to create an iframe dynamically using JavaScript, and we will have to append it to the DOM of our HTML page, for which we can either simply add the iframe to the <body> tag like in the above example, or we can add the iframe inside a particular div tag.

Can we access Dom in iframe?

The contentWindow property returns the Window object of an HTMLIFrameElement. You can use this Window object to access the iframe's document and its internal DOM.

Is an iframe a DOM element?

The IFrame Object property in HTML DOM is used to create and access the <iframe> element within the object. An inline frame is used for embedding another document within the current HTML document.


2 Answers

Here you go:

var iframe;

iframe = document.createElement('iframe');
iframe.src = 'http://example.com/file.zip';
iframe.style.display = 'none';
document.body.appendChild(iframe);

Live demo: http://jsfiddle.net/USSXF/2/

Your code doesn't work because you're passing an entire HTML string into the createElement function ("jQuery style" :)), which is invalid. The valid parameter for this function is a string representing the tag-name (like 'div', 'iframe', 'p', etc.).

Read about document.createElement here.

like image 178
Šime Vidas Avatar answered Sep 24 '22 11:09

Šime Vidas


You need to append the node to the DOM using document.appendChild

You also need to escape your inner single-quotes or use double-quotes instead.

like image 20
Jeff Avatar answered Sep 21 '22 11:09

Jeff