dahui
dahui

Reputation: 2166

Cannot programmatically populate an iframe with Javascript

I want to dynamically populate an iframe with Javascript.

I do not want the iframe in a html document loaded in via src.

I do not want to use Jquery, just plain old javascript (ECMA 5.1).

Here is my code so far:

var elementToAttachTo = document.getElementById(attachTo);

// Need to create and attach iframe to page before populating.
// attachTo is provided as a parameter to this function, this definitely
// works as I got this working setting the iframe src to a html file..

var ifrm = document.createElement("iframe");
ifrm.setAttribute("id", "blabla");
// I set src to about:blank here, cause I read to do that somewhere...
ifrm.setAttribute("src", "about:blank");

// I attach the iframe BEFORE populating it.
elementToAttachTo.appendChild(ifrm);

ifrm = populateIframe(ifrm);

Here is my populateIframe function:

function populateIframe(iframe) {
    var ifrmHtml = iframe.contentDocument.documentElement;

    var p = document.createElement("p");
    p.innerHTML = "Hello iframe!";
    ifrmHtml.appendChild(p);

    iframe.contentDocument.documentElement = ifrmHtml;
    return iframe;
}

I was trying to call appendChild() directly to the iframe which didn't work, so I did some research and found examples of appending to the contentDocument.documentElement. It still doesn't work.

Many thanks for any help!

Upvotes: 1

Views: 765

Answers (1)

Nikola Mitic
Nikola Mitic

Reputation: 1492

You missed to append iframe content to the body.

function populateIframe(iframe) {
    var ifrmHtml = iframe.contentDocument.documentElement.querySelector('body');

    console.log(ifrmHtml)

    var p = document.createElement("p");
    p.innerHTML = "Hello iframe! Ja sam faca";
    ifrmHtml.appendChild(p);

    iframe.contentDocument.documentElement = ifrmHtml;
    return iframe;
}

See here --> https://jsfiddle.net/nmitic/24ejkfnw/

Upvotes: 1

Related Questions