Skip to content Skip to sidebar Skip to footer

Where Do The Javascript `style` Property Names Come From?

I have been learning about changing css options via javascript, like: document.getElementById('sweetDiv').style.fontSize and ...style.backgroundColor, whose naming conventions seem

Solution 1:

MDN says of cssFloat:

Note: If you're referring to this property from JavaScript as a member of the element.style object, you must spell it as cssFloat. Also note that Internet Explorer versions 8 and older spelled this styleFloat. This is an exception to the rule that the name of the DOM member is the camel-case name of the dash-separated CSS name (and is due to the fact that "float" is a reserved word in JavaScript, as with the need to escape "class" as "className" and escape 's "for" as "htmlFor").

This is because ECMAScript 3 disallowed property access with a dot operator if the property name was a reserved word in the language. For example, doing foo.function or bar.if raised an error. Similarly, float was a reserved word in ES3 (in the expectation that it may be used by the language in the future), so any access of the form baz.float was syntactically invalid.

To compensate for this, browsers used cssFloat (or styleFloat in IE8) to avoid having a property named float. This is the only exception I know of for the style object, though the note above includes some others that exist elsewhere in the DOM specification. For all other properties, simply use the normal syntax conversion of "camel-cased version of the hyphenated CSS name." this conversion is formalized in the CSSOM spec as the "CSS property to IDL attribute algorithm" (and vice versa for the reverse).

In summary, you don't need a specific reference for the object in each style property (namely, the CSSStyleDeclaration type) in JavaScript, because it's no different from information about CSS rule names generally. The one single exception is cssFloat, and you've obviously already found that one.

If you interested in a complete listing of all supported property names for style in any given browser, do Object.keys(document.createElement("div").style).

Solution 2:

From WC3: Note: The CSS "float" property is called "cssFloat" in JavaScript, because "float" is a reserved word in JavaScript.

So 99.9% of styles will just be style.whatever, cssFloat is a special exception to this rule.

You can find the exhaustive CSS specifications here: https://www.w3.org/Style/CSS/specs.en.html but be warned, it's not very friendly to the reader.

Post a Comment for "Where Do The Javascript `style` Property Names Come From?"