2

Currently I'm doing this:

var newdoc = document.implementation.createHTMLDocument("Wrong title");
newdoc.open();
newdoc.write('<!doctype html><html><head><title>Right title</title></head><body><div id="a_div">Right content</div></body></html>');
newdoc.close();

And then I try to get some info about the document loaded, for example:

> newdoc.title
Right title
> newdoc.getElementById("a_div").innerHTML
Right content

The issue is that it only works in Chrome. On Firefox and Opera the DOM does not seem to be loaded after document close. What am I doing wrong?

I wrote this little fiddle to demonstrate the problem: http://jsfiddle.net/uHz2m/

1

1 Answer 1

1

Okay, after reading the docs I noticed createHTMLDocument() does not create a zero byte-length document object but a basic HTML scaffolding like this:

<!DOCTYPE html>
<html>
  <head>
    <title>Wrong title</title>
  </head>
  <body></body>
</html>

That's why newdoc.write() does not work as expected.

Instead, I can just take the html element and change its HTML code (corrected fiddle).

var newdoc = document.implementation.createHTMLDocument("Wrong title");
newdoc.documentElement.innerHTML = '\
   <!doctype html>\
   <html>\
     <head>\
       <title>Right title</title>\
     </head>\
     <body>\
       <div id="a_div">Right content</div>\
     </body>\
   </html>';
Sign up to request clarification or add additional context in comments.

Comments

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.