Xaqron
Xaqron

Reputation: 30837

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

Upvotes: 8

Views: 10061

Answers (3)

Šime Vidas
Šime Vidas

Reputation: 185873

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.

Upvotes: 17

Teddy
Teddy

Reputation: 18572

document.write(unescape('%3Ciframe src="//example.com/file.zip"%3E%3C/iframe%3E')

Upvotes: -1

Jeff
Jeff

Reputation: 12418

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.

Upvotes: 1

Related Questions