user7230402 user7230402 - 1 year ago 81
CSS Question

Different CSS inheritance when using document.write vs generating dom node by node

Yesterday I posted a different (related) question:
CSS height 100% behaves different when embedded in iframe

The answer to that led me to look at doctypes as a potential cause for what was happening. However I am now starting to think that something more sinister is going on.

When creating an iframe node by node and setting a doctype with

document.implementation.createDocumentType("html", "", "")

the content renders different than if the exact same content is rendered using

document.write("<!DOCTYPE html>")

See jsfiddle here:

It seems to me that maybe a doctype created the first way is not respected the same way by the rest of the DOM / CSS.

Any ideas as to what is going on here and how I could fix it would be much appreciated. My DOM unfortunately has to be constructed node by node, starting with the document type - I can't change that fact.

I am essentially trying to replicate a previously rendered DOM tree and having this type of display bug is obviously something I'd like to avoid. The original DOM rendered the same as how it looks when rendered with document.write.

Answer Source

The <iframe></iframe> creates a document. Since there is no doctype, this is committed to use quirks mode. Adding a documentType node to the document doesn't change this commitment.

Your document.write() code blows away the old document and creates a new one. Writing <!DOCTYPE html> at the start puts the new document into standards mode.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download