Using Javascript how can I identify the element at a given position? Basically I'm looking to write a function that takes two input parameters (the x and y coordinates) and returns the html element at the position on the screen represented by the parameters.
-
3[elementsFromPoint](https://developer.mozilla.org/en-US/docs/Web/API/Document/elementsFromPoint) – Janus Troelsen May 24 '16 at 12:48
3 Answers
document.elementFromPoint(x, y)
document.elementsFromPoint(x, y)
https://drafts.csswg.org/cssom-view/#dom-document-elementfrompoint
https://developer.mozilla.org/en-US/docs/Web/API/Document/elementFromPoint https://developer.mozilla.org/en-US/docs/Web/API/Document/elementsFromPoint

- 14,854
- 11
- 100
- 103

- 184,426
- 49
- 232
- 263
-
3
-
I have tried this method and it measure the position according to the document. How do I use it relative to the parent element ? – Charas Sep 08 '15 at 10:44
-
If at the coordinate x, y, there is a frame or iframe you will get the frame, rather than the element at that location. – Elmue Sep 14 '15 at 21:57
-
A jsfiddle example would be really awesome! Seems amazing! Can't wait to try it! – www139 Oct 12 '15 at 03:59
-
Quite amazing this exists, I develop for like 10 years and never heard of this function, thanks. – Red Mar 18 '22 at 15:17
You can use the native JavaScript elementFromPoint(x, y)
method, that returns the element at coordinates x,y in the viewport.
See the elementFromPoint w3c draft
And, a code sample:
function changeColor(newColor) {
// Get the element placed at coords (2, 2)
var elem = document.elementFromPoint(2, 2);
// Set the foreground color to the element
elem.style.color = newColor;
}
<p id="para1">Change this text color using the following buttons.</p>
<button onclick="changeColor('blue');">Blue</button>
<button onclick="changeColor('red');">Red</button>
You can use setInterval()
to continuously check the element's hover event but it's not recommended, try to use .hover(...)
and css instead to enhance the application performance.

- 793
- 7
- 20
To get the topmost element at a specific position relative to the viewport, document.elementFromPoint(x, y)
can be used.
To obtain an array of all the elements at a specific position, use document.elementsFromPoint(x, y)
.
In both cases, x
is the horizontal coordinate which is relative to the left of the viewport and y
is the vertical coordinate which is relative to the top of the viewport.

- 76,500
- 11
- 62
- 80
-
Hi @Unmitigated this method seems to not be available anymore (tried Chrome in linux and in mac), do you know with what it might have been replaced ? – George Pligoropoulos Jan 31 '23 at 11:54
-
@GeorgePligoropoulos It still works for me. Could you provide a [mre]? – Unmitigated Feb 01 '23 at 04:00
-
believe it or not it was a typo. so please disregard my comment. many thanks – George Pligoropoulos Feb 06 '23 at 17:27