0

My element has the following CSS style:

#span {
  position: absolute;
  top: 100px;
  left: 10px;
}

Is there a way to read the position type with JavaScript? I've tried these two approaches:

document.getElementById("span").getBoundingClientRect()
document.getElementById(id).style.position

Neither fetches the position. Is there a better way to go about doing it or an actual way to do it?

D M
  • 5,769
  • 4
  • 12
  • 27

1 Answers1

2

Yes, you can use Window.getComputedStyle() with a reference to your element to get the value of styles applied via CSS.

The Window.getComputedStyle() method returns an object containing the values of all CSS properties of an element, after applying active stylesheets and resolving any basic computation those values may contain.

The important part is that all stylesheets are factored in.

const foo = document.getElementById('foo');

console.log(`foo.style.position: ${foo.style.position}`);
console.log(`foo.style.top: ${foo.style.top}`);
console.log(`foo.style.left: ${foo.style.left}`);

console.log(`getComputedStyle(foo).position: ${getComputedStyle(foo).position}`);
console.log(`getComputedStyle(foo).top: ${getComputedStyle(foo).top}`);
console.log(`getComputedStyle(foo).left: ${getComputedStyle(foo).left}`);
#foo {
  position: absolute;
  top: 100px;
  left: 10px;
}
<div id="foo">Hello, there!</div>

If you're after the actual location on the page instead of the value of the styles applied, you should check out Retrieve the position (X,Y) of an HTML element.

D M
  • 5,769
  • 4
  • 12
  • 27