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.