Categories
JavaScript Answers

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

Spread the love

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

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

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

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

For instance, we write

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

to call getElementById to select the element we want to get the position for.

Then we call getBoundingClientRect on it to get an object with the position values.

And then we can get the top and left position offset with the top and left properties.

Conclusion

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

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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