Categories
JavaScript Answers

How to Get the Element at the Specified Position with JavaScript?

Spread the love

We can use the document.elementFromPoint method to get the element at the given x-y coordinates.

Each coordinates is in pixels.

For instance, if we have the following div element:

<div>  
  hello world  
</div>

Then we can use the document.elementFromPoint method to get the div by writing:

const el = document.elementFromPoint(10, 10);  
console.log(el)

The coordinates are relative to the top left corner.

The first argument is the x coordinate and the 2nd argument is the y coordinate.

So the first argument is 10 pixels to the right of the top left corner.

And the 2nd argument is 10 pixels below the top left corner.

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 *