How do I get the top style value with javascript?

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
    
    
<style>
    #playerOne{position:absolute;top:500px;left: 500px;border:3px solid green; height: 500px;width:500px; background-color:black}   
</style>
</head>

<body>
    <div id="main">
    <div id="playerOne"></div>
    
    </div>  
<script>
var playerOneDiv = document.querySelector("#playerOne");    
    
console.log(playerOneDiv.style.top);

    
</script>   
</body>
</html>

I am not getting anything in my console when I try it like this

I am trying to mimic w3schools example but am having no luck with it, thank you.

http://w3schools-fa.ir/jsref/prop_style_top.html

1 thought on “How do I get the top style value with javascript?”

  1. the issue is window imposing style from style sheet after display rendered. If you grab the window property you would be able to get imposed style properties. Please try by updating your script using following code:

    <script>
        var playerOneDiv = window.getComputedStyle(document.querySelector("#playerOne")).top;
        console.log(playerOneDiv);
    </script>
    

    I hope this will help you. Thank you.

    Reply

Leave a Comment