Sometimes, we want to get the X and Y coordinates for a div element with JavaScript.
In this article, we’ll look at how to get the X and Y coordinates for a div element with JavaScript.
How to get the X and Y coordinates for a div element with JavaScript?
To get the X and Y coordinates for a div element with JavaScript, we an use the getBoundingXClientRect
method.
For instance, we add a div by writing:
<div>
hello world
</div>
Then we write:
const element = document.querySelector('div');
const position = element.getBoundingClientRect();
const x = position.left;
const y = position.top;
console.log(x, y)
to select the div with querySelector
.
And then we call getBoundingClientRect
to get the position of the div.
Then we get the x and y coordinates of the div with position.left
and position.top
.
Conclusion
To get the X and Y coordinates for a div element with JavaScript, we an use the getBoundingXClientRect
method.