how to get style values with js

so i have a simple html file which consists of a div; and a css file which has a simple styling for the mentioned div:

html :

<html>
<head>
    <title>Simple Movement</title>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="style.css"/>
    <script src="index.js"></script>
</head>

<body>
    <div id="square"></div>
</body>
</html>

css:

body {
    margin: 0;
}

#square {
    width: 100px;
    height: 100px;
    border: 1px solid #095057;
    background-color: #20979e;
    position: absolute;
    left: 200px;
    top: 200px;
}

in my js file i do a simple log as follows:

console.log(document.getElementById('square').style.top)

but i receive an error:

   Uncaught TypeError: Cannot read properties of null (reading 'style')
at index.js:1

i have no idea why it says style is null.do you?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

i have no idea why it says style is null.do you?

It doesnt.
It says document.getElementById('square') returns null so youre reading the property style on null which results in the error.

That happens because your script is loaded (and executed) in the head. At this point the element with the ID “square” isnt existent in the DOM yet.

Move your script to below your element (see snippet) or mark it with async defer like this: <script src="index.js" async defer></script> to make it load and execute after DOM parsing is done.

Also accessing style will only show inline styles from the style attribute so that wont get you values from your stylesheet file (or inline stylesheets).

Use computedStyleMap() (see https://developer.mozilla.org/en-US/docs/Web/API/Element/computedStyleMap) to get the actual computed styles including all stylesheets.

body {
  margin: 0;
}

#square {
  width: 100px;
  height: 100px;
  border: 1px solid #095057;
  background-color: #20979e;
  position: absolute;
  left: 200px;
  top: 200px;
}
<html>

<head>
  <title>Simple Movement</title>
  <meta charset="UTF-8">
</head>

<body>
  <div id="square"></div>
  
  <script>
    console.log(document.getElementById('square').computedStyleMap().get('top').value);
  </script>
</body>



</html>


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x