document.write
seems to figure out on its own when to write to the head and when to write to the body.
For example, it writes <style>
and <script>
to the head and <div>
to the body.
Can this automatic behavior be avoided and let the programmer decide what goes where?
I experimented this with iframes. Unfortunately, the internal code box here doesn't seem to support interacting with iframes, so please see it in JSFiddle.
var theiframe=document.getElementById('testing'), output=document.getElementById('output'), thebody=document.getElementById('output_body'), thehead=document.getElementById('output_head'), thebody=document.getElementById('output_body');
console.clear();
console.group('Testing');
theiframe.contentWindow.document.open();
theiframe.contentWindow.document.writeln("<script>var foo1='head';<\/script>");
theiframe.contentWindow.document.writeln("<script>var foo2='body';<\/script>");
theiframe.contentWindow.document.close();
console.log(theiframe.contentWindow.document.documentElement);
thehead.value = theiframe.contentWindow.document.head.innerHTML;
thebody.value = theiframe.contentWindow.document.body.innerHTML;
console.groupEnd();
textarea {width: 50%}
Iframe:
<br /><iframe id="testing"></iframe>
<hr>
Iframe's head:
<br /><textarea id="output_head"><</textarea>
<hr>
Iframe's body:
<br /><textarea id="output_body"><</textarea>