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

Question:

I have a code something like this:

.position{
 position:relative
}
<div class="position" id="position"></div>
document.getElementById('position').style.position

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!

Answer:

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

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

Example:

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