PageYe PageYe - 1 month ago 5
CSS Question

how "document.createElement" works to "display" property

I found a interesting phenomenon and it performs different in Firefox from Chrome.

open you browser devTool with F12 and type this.

var span=document.createElement("span");
document.defaultView.getComputedStyle(span).display;


it returns "block" in Firefox and
""
in Chrome .
The first time I met the case was in Firefox and it amazed me that the result was "block"! However, when
document.body.appendChid(span)
,it was ok.

I searched in MDN but withot any harvest in the end.I guess the
document.defaultView.getComputedStyle
is influenced by the browser's rendering engine.The "display" property is set after that the element has rendered by the rendering engine to the DOM tree.And the gecko(Firefox) gives a default value to it as "block" while the webkit(Chrome) sets it "".

can anyone give a more detailed explaination?

Answer

That's because the spec does not specify whether elements outside the DOM have computed styles or not.

Firefox thinks they do. And they are affected by stylesheets in the document.

console.log(getComputedStyle(document.createElement('div')).color);
// rgb(0, 0, 255) on Firefox
div { color: blue; }

Chrome thinks they don't, so returns the empty string. You need to append them to the document in order to use getComputedStyle.

This was discussed in www-style: computedStyle of cloneNode