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>');
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With