javascripthtmlcssstylesheetgetcomputedstyle

why are initial CSS styles not visible on DOM element.style field?


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>


Solution

  • 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>