Darshan Rivka Whittle
Darshan Rivka Whittle

Reputation: 34061

What is the correct way to access an element's CSS style properties from JavaScript?

The following JavaScript code works perfectly in WebKit-based browsers, but it doesn't work in Firefox:

canvas.style['left'] = "50%";
canvas.style['margin-left'] = "-" + (width / 2) + "px";

Inspecting the element in Firefox, I can see that the left property was successfully set by the above code, but the element has no margin-left property for some reason.

It seems I must be doing something wrong, which isn't surprising, because I haven't been able to figure out what the correct way to access (read or set) CSS style properties from JavaScript is. I've just found some examples using this notation and tried to follow them, with these mixed results.

What is the correct / standards-compliant way to access an element's CSS style properties from JavaScript?

Upvotes: 1

Views: 300

Answers (2)

abuduba
abuduba

Reputation: 5042

Remove dash and next ones words with a capital letter, margin-left to marginLeft etc

  obj.style.marginLeft = '10px';

Upvotes: 0

Darshan Rivka Whittle
Darshan Rivka Whittle

Reputation: 34061

After much hair-pulling, I unearthed the following basic facts that are sure to be no-brainers to most JavaScript folks, but I imagine my confusion is not uncommon among others very new to JavaScript.

  • All objects in JavaScript are associative arrays.

Object properties can be accessed in either of two ways:

var o = new Object();
o.prop = "A string";
o['prop']; // => "A string"

While it is possible to use an object as a "normal" associate array and use keys with arbitrary strings:

o.['another-prop'] = 4 // Perfectly valid

in doing so, you would create a property that could not be accessed via the dot notation:

o.another-prop // Parsed as `o.another` minus `prop`

This is presumably the reason for:

  • DOM style properites use camelCase when accessed from JavaScript.

I was using the hyphenated property names used in CSS. These worked in all the WebKit-based browsers I tested, but it seems that is only because WebKit is forgiving.


So as far as I can tell, the correct way to access CSS style properties from JavaScript is to convert the property name to camel case, and then use either dot notation or bracketed associative array notation. The line that didn't work in Firefox becomes

canvas.style['marginLeft'] = "-" + (width / 2) + "px";

or

canvas.style.marginLeft = "-" + (width / 2) + "px";

That works for me in all browsers I've tested, but if something I've said isn't correct or consistent with the standards, I'd love to hear it.

Upvotes: 1

Related Questions