How to obtain with Javascript the value of the properties applied to an element with CSS?


I have a code something like this:

<div class="position" id="position"></div>

Result is ""

But if I put it directly in the HTML

<div id="position" style="position:absolute"></div>

Result is "absolute".

I have already made the JS run when the document is loaded with DOMContentLoaded

I would like to know why, thank you very much!


If you need to get the styles applied " inline " to an element, you can use .

But, if you need to get the styles applied with CSS and " inline " to an element, you can usewindow.getComputedStyle()


let element = document.getElementById('element');
let compStyles = window.getComputedStyle(element);

console.log('Element postion = ', compStyles.getPropertyValue('position'))
console.log('Element z-index = ', compStyles.getPropertyValue('z-index'))
.position {
  position: relative;
<div class="position" id="element" style="z-index: 1"></div>
Scroll to Top