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

Spread the love

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.

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 top, right, bottom, and left position from the object returned.

Conclusion

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

Leave a Reply

Your email address will not be published. Required fields are marked *