1

I am creating an Iframe and trying to add Html to it's body, butI constantly get an error Cannot read property body of null.

My code looks something like this:

var frameToPrint = document.createElement("IFRAME") as HTMLFrameElement;
frameToPrint.contentDocument.body.innerHTML = "";
It works if I add the Iframe to my HTML and then get it using GetElementById, but I cannot have this Iframe displayed on my page. Even hidden, it messes up my dimensions.

Thank you in advance!

1
  • Have you tried to add the body as html first? The Iframe is just an empty container without anything in it, so it doesn't know that it's supposed to be html, which means it doesn't have a body on creation. Commented Oct 19, 2018 at 10:40

2 Answers 2

1

I found the answer. You need to append the new created frame to your body. That initializes the contentWindow and the contentDocument of the iframe.

var frameToPrint = document.createElement("iframe");
frameToPrint.setAttribute("name", "prnt");
document.body.appendChild(frameToPrint);

Sign up to request clarification or add additional context in comments.

1 Comment

"It works if I add the Iframe to my HTML and then get it using GetElementById, but I cannot have this Iframe displayed on my page."
0

The iframe is an empty element on creation. It doesn't know that it is supposed to be (for you) an html-document. Therefore it has no body you can append to.

Down there I have snippet as an example.


  1. create the iframe-element: var iframe = document.createElement("iframe");
  2. create the body-element: var body = document.createElement("body");
  3. create the content you want to append: ex.: var body = document.createElement("body");
  4. Fill your content with actual content: content.textContent = "Some Text";

And after that you just append it accordingly to your iframe-element

var iframe = document.createElement("iframe"); 
var body = document.createElement("body");
var content = document.createElement("p");
content.textContent = "Some Text";

body.appendChild(content);
iframe.appendChild(body);

console.log(iframe.innerHTML);

2 Comments

That won't work. The Iframe has it's own content window and content document that should have standard html structure.
Yea, but he won't append it to his own HTML, therefore he has no DocumentStructure on it, which means this would be the way to go, or am I missing something?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.