151

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.

kjv
  • 11,047
  • 34
  • 101
  • 140

3 Answers3

271
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

Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
rahul
  • 184,426
  • 49
  • 232
  • 263
  • 3
    I'm amazed this worked in ie 5.5 and is not used that much today. – Vlad Nicula Jan 20 '15 at 14:32
  • 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
29

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.

Andrés Morales
  • 793
  • 7
  • 20
6

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.

Unmitigated
  • 76,500
  • 11
  • 62
  • 80