How to get the position of a div/span tag with JavaScript?

Spread the love

Sometimes, we want to get the position of a div/span tag with JavaScript.

In this article, we’ll look at how to get the position of a div/span tag with JavaScript.

How to get the position of a div/span tag with JavaScript?

To get the position of a div/span tag with JavaScript, we use the getBoundingClientRect method.

For instance, we write

const { top, left } = document.getElementById("foo").getBoundingClientRect();

to select the element with getElementById.

Then we call getBoundingClientRect to return an object with the position of the element.

We use top to get the top position.

And use left to get the left position.

Conclusion

To get the position of a div/span tag with JavaScript, we use the getBoundingClientRect method.

Leave a Reply

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