3

OK I have full expectation of going down in flames for asking something stupid (or at least duplicate), but in the attached snippet, why do I have to use window.getComputedStyle to access styles applied by CSS? I was under the impression that the .style field would at least reflect those styles initially applied by CSS, and/or manually changed since then.

If not, what are the exact rules governing which properties are reflected (and when) in an element's .style field?

setTimeout(() => {
    console.log("the bckg color:", reddish.style.backgroundColor);
    console.log("the width:", reddish.style.width);
    console.log("from a computed style:", window.getComputedStyle(reddish).backgroundColor);
    console.log("from a computed style:", window.getComputedStyle(reddish).width);
}, 100);
#reddish {
    background-color: #fa5;
    width: 100px;
    height: 100px;
}
<html>
    <body>
        <div id="reddish"></div>
    </body>
</html>
AndrewL64
  • 13,967
  • 6
  • 36
  • 64
Labrador
  • 447
  • 3
  • 11

2 Answers2

4

HTMLElement.style is for the inline style of an element. It does not take into account CSS whatsoever. This is basically just directly setting or getting a property on the element object.

<div style="color: red;">Hello</div>

Window.getComputedStyle() takes into account inline styles and CSS, after resolving cascading, inheritance, etc. It's basically the "final" actual style value used to render the element on the page.

// CSS
#blue-text {
  color: blue !important;
}

// HTML
<div style="color: red;" id="blue-text">Hello</div>

// JS
const myElement = document.querySelector("#blue-text");
myElement.style.color; // "red" because that's the inline style
window.getComputedStyle(myElement).color; // "rgb(0, 0, 255)" because CSS !important overrides inline style
jered
  • 8,946
  • 2
  • 16
  • 30
  • OK, so basically, I can trust `HTMLElement.style` if and only if either either: (a) I am accessing a style property that was defined inline (and not overridden by some `!important` CSS declaration), or (b) I am accessing a style property that was previously set via `element.style.property = ...`? – Labrador Jan 23 '19 at 07:08
  • Basically yeah. – jered Jan 23 '19 at 07:09
  • @Labrador that depends what you expect it to mean. You can't **ever** trust Element.style to return the applied value of a CSS property. It can very well be overridden by an `!important` rule somewhere else, or even just be some value with no real meaning like `"auto"`. – Kaiido Jan 23 '19 at 07:19
  • ...except that using `element.style.property = ...` still does not override an `!important` CSS style, apparently. So the rule is really: using `HMTLElement.style` is like editing the inline `style` attribute of the element, nothing more. (@Kaiido our comments crossed. Thanks.) – Labrador Jan 23 '19 at 07:20
4

The HTMLElement.style property is not useful for completely learning about the styles applied on the element, since it represents only the CSS declarations set in the element's inline style attribute, not those that come from style rules elsewhere, such as style rules in the section, or external style sheets. To get the values of all CSS properties for an element you should use Window.getComputedStyle() instead.

Via- MDN Web Docs | Getting Style Information


HTMLElement.style:

The HTMLElement.style property is used to get as well as set the inline style of an element.

console.log(document.getElementById("para").style.fontSize); // will work since the "font-size" property is set inline
console.log(document.getElementById("para").style.color); // will not work since the "color" property is not set inline
#para {color: rgb(34, 34, 34);}
<p id="para" style="font-size: 20px;">Hello</p>

Window.getComputedStyle():

The getComputedStyle() method however, returns an object containing the values of all CSS properties of an element, after applying active stylesheets and resolving any basic computation those values may contain thus returning the css properties from both inline style declarations as well as from external style-sheets.

console.log(window.getComputedStyle(document.getElementById("para")).fontSize); // will work
console.log(window.getComputedStyle(document.getElementById("para")).color); // will work
#para {
  color: rgb(34, 34, 34);
}
<p id="para" style="font-size: 20px;">Hello</p>
AndrewL64
  • 13,967
  • 6
  • 36
  • 64
  • You should probably have quoted [this paragraph](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style#Getting_style_information) instead. Ps: quote blocks are supported in the editor. – Kaiido Jan 23 '19 at 07:26
  • @Kaiido Indeed. Let me update the answer. Thanks for the heads up man. – AndrewL64 Jan 23 '19 at 07:28