9

For example, we need to access body's padding-right

let el = document.querySelector('body');
let style = window.getComputedStyle(el);

Thanks to this explanations, it's clear that it could be safely done by:

style.paddingRight

or

style.getPropertyValue('padding-right')

But, it seems that this also works fine:

style['padding-right']

Is there are any differences? Thx

user2864740
  • 60,010
  • 15
  • 145
  • 220
MaxCore
  • 2,438
  • 4
  • 25
  • 43
  • FWIW: https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle -> https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration -> https://drafts.csswg.org/cssom/#cssstylesheet – user2864740 Jun 13 '19 at 18:16
  • This answer (https://stackoverflow.com/q/31506401/2864740) talks about historic and current guarantees wrt. the object models. – user2864740 Jun 13 '19 at 18:20
  • (Also, in JS, `x["y"]` behaves the *same* as `x.y`, where y is a valid identifier - so asking about []-notation is basically asking if the object exposes *properties* with given names.) – user2864740 Jun 13 '19 at 18:21

3 Answers3

14

One difference is that getPropertyValue is guaranteed to return a string, while with the direct property access (JavaScript's bracket or dot notation) you could get undefined. getPropertyValue will return the empty string in that case.

let el = document.querySelector('body');
let style = window.getComputedStyle(el);

console.log(style.something === style.getPropertyValue('something')); // false
trincot
  • 317,000
  • 35
  • 244
  • 286
2

Is there a difference:

1) Yes

[] - Accessing properties using bracket notation like this: style['padding-right'] is defined in the runtime specification of JavaScript (ECMAScript). It is a well known mechanism for accessing properties on objects: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors

getPropertyValue() - is specified in the CSSOM specification as a method for accessing CSS properties from a CSS style object.

2) No - not at all for practical purposes

3) Yes and No - opinions will flare about best practices etc. It is entirely possible (although not probable) the CSSOM specification may change and store that property in some other location on the object. That would render the brackets useless in your code and break.

Randy Casburn
  • 13,840
  • 1
  • 16
  • 31
-1

Reason why style['padding-right'] also works.

>function A() { this.a = 5;}
//undefined
>a = new A()
//A {a: 5}
>a['a']
//5

Difference already mentioned by @trincot.