-1

I wanted to use getComputedStyle to access css properties, unfortunately it only console.log()'s standard properties.

Below you will find my code.

On the picture you will find what it logs.

logs


<body>
    <div id="box">box</div>


    <script>
        const box = document.getElementById("box");
        
        const boxCS = window.getComputedStyle(box)
        
        console.log(boxCS.zIndex)
        </script>
</body>

<style>
    #box {
    width: 100px;
    height: 100px;
    border: 1px solid black;
    position: absolute;
    z-index: 1;
    background-color: rgb(200, 200, 200);
}
</style>
Ouroborus
  • 16,237
  • 4
  • 39
  • 62
  • Because you put your style tag after the script tag (in fact outside the body which isn't even valid). – CherryDT Nov 29 '22 at 09:18
  • Related: [Why does jQuery or a DOM method such as `getElementById` not find the element?](/q/14028959/4642212). The current best practice is to include your JavaScript code as a [module](//developer.mozilla.org/en/docs/Web/JavaScript/Guide/Modules) using `` which solves this problem and many more. – Sebastian Simon Nov 29 '22 at 12:47

2 Answers2

2

Your script is running before the rendering of the DOM is complete. Try wrapping your preset in an event-listener. That way it's irrelevant in which order scripts and styles are inlined or loaded externally.

Example

window.addEventListener("DOMContentLoaded", () => {
    const boxElement = document.getElementById("box");
    const boxStyle = window.getComputedStyle(boxElement)
        
    console.log(boxStyle.zIndex)
});

Refer to the MDN documentation on DOMContentLoaded for details.

idleberg
  • 12,634
  • 7
  • 43
  • 70
-1

One of the reasons is that you declare styles after the script. If you put it before script, it'll be okay. Example

Animus
  • 665
  • 12
  • 24