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
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
Share Improve this question edited Jun 13, 2019 at 18:15 user2864740 61.9k15 gold badges157 silver badges227 bronze badges asked Jun 13, 2019 at 18:09 MaxCoreMaxCore 2,7386 gold badges29 silver badges49 bronze badges 3 |3 Answers
Reset to default 15One 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
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.
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.
x["y"]
behaves the same asx.y
, where y is a valid identifier - so asking about []-notation is basically asking if the object exposes properties with given names.) – user2864740 Commented Jun 13, 2019 at 18:21