Does your browser support CSS on newborns ?

CSS T Shirt
CSS for every ocassion

Working on a cross browser code the other day, I stumbled upon yet another difference in browsers behaviour and dom+javascript implementation. (first published 26OCT09) The difference is in handling CSS properties on the “newborn” elements, while they are still detached from the document.

Above code works in IE & FF, but not in CHROME (see the re-check update bellow). This is because CHROME implementation does not allow setting/getting style properties on the newly made and detached DOM elements. So if one uses (for example) getComputedStyle(),on this kind of elements, the one will receive nothing, aka empty string. While in FF1 , the one will be able to do CSS related operations on newly made detached elements. This is also true when using jQuery. The following code will not work in CHROME, because of the same reason:

This has to be “taken care of”. Libraries like jQuery (and my own “DBJ”) should “know” there is this issue in existence. So that code , like the one above works. To solve his issue, in the context of my library I have added this feature check also. I am calling it css_on_newborns:

(Slightly) moot point is , if the document.createElement(), above will work before the dom is “ready” to be used , and after a page load? As every other library author (for example the author of Sizzle) I am pretty sure this will work, any time browser is ready for the javascript to be parsed and executed. Hence, the code does it “there and then” and leaves the result in a property. One could imagine a function which will do this check only once and return the result on each consecutive call, but in this case that would be an overkill.

Update 27OCT12

Just checked my Chrome (Version 22.0.1229.94). And … yes, this is still the case in Chrome. If You create DOM element in code, change it’s style in code and then read the values You just have changed, the style object properties will read as empty strings. Just like the source on the top of the post shows.


1: I should mention here that this does not apply to IE since ie has no getComputedStyle() method available.Update: IE9 and better has this method avaliable. And yes it natively supports css on newborns.

2 thoughts on “Does your browser support CSS on newborns ?”

Comments are closed.