简体   繁体   中英

Adding iframe and paragraph elements dynamically

I want to add iframe element to the page and then add <p> element inside that iframe.
I tried this:

var iframe = document.createElement('iframe');
iframe.frameBorder = 1;
iframe.width = "500px";
iframe.height = "250px";
iframe.id = "iframe";

var p = document.createElement('p');
iframe.appendChild(p);
document.getElementById("div").appendChild(iframe); //this is a div  that I have in body.

The iframe is added to the page but P is not added into iframe(iframe's body)

In modern browsers, you use the contentDocument attribute. In others, you have to use contentWindow.document. You create the paragraph using the iframe's document, in the onload event. So:

var iframe = document.createElement('iframe');
iframe.frameBorder = 1;
iframe.width = "500px";
iframe.height = "250px";
iframe.id = "iframe";

iframe.onload = function()
{
    var doc = iframe.contentDocument || iframe.contentWindow.document;
    var p = doc.createElement('p');
    p.textContent = "Paragraph in iframe";
    doc.body.appendChild(p);
};

document.getElementById("div").appendChild(iframe); //this is a div  that I have in body.

I made a jsfiddle demo .

Also, I recommend you don't use ids that are the same as the tag name. It could become confusing.

hopefully this will get you going in the right direction:

var p = document.createElement('p');

var iFrmDocument = (iframe.contentWindow || iframe.contentDocument);
if (iFrmDocument.document) iFrmDocument=iFrmDocument.document;
iFrmDocument.appendChild(p);

document.getElementById("div").appendChild(iframe);

Does that make sense? It's a bit of a necessary detour when dealing with [i]Frames

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM