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 can use the getBoundingClientRect method.

For instance, we write

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

to call getBoundingClientRect to get an object with the position of the element.

And then we get the top, right, bottom, and left positions.

Conclusion

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

Leave a Reply

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