Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between getPropertyValue() and the bracket notation [] for CSSStyleDeclaration?

Tags:

javascript

css

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

like image 921
MaxCore Avatar asked Jun 13 '19 18:06

MaxCore


1 Answers

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
like image 136
trincot Avatar answered Oct 17 '22 22:10

trincot