Menu Close

How to retrieve the position (X,Y) of an HTML element with JavaScript?

retrieve

Sometimes, we want to retrieve the position (X,Y) of an HTML element with JavaScript.

In this article, we’ll look at how to retrieve the position (X,Y) of an HTML element with JavaScript.

To retrieve the position (X,Y) of an HTML element with JavaScript, we use the getBoundingClientRect method.

For instance, we write

const { top, right, bottom, left } = element.getBoundingClientRect();
console.log(top, right, bottom, left); 

to call the element.getBoundingClientRect method to return the position of the element. We get the toprightbottom, and left position from the object returned.

Posted in HTML, JavaScript

You can also read...