How do I find the DOM node that is at a given (X,Y) position? (Hit test)

As long as your users aren’t using old versions of Safari, Chrome or Opera, you’re in luck: use document.elementFromPoint(x, y) (MSDN ref, Mozilla ref, QuirksMode article):

Returns the element from the document
… which is the topmost element which
lies under the given point.

If you need to support older browsers, I can’t think of many options other than what you suggest (traverse the entire DOM, looking at element positions and sizes and seeing if any of them encapsulate your (x, y)).

I don’t think the event simulation will work but it is an interesting idea. My understanding of event dispatching is you specify the target that the event is for, which is precisely what you are trying to find out in the first place.

Leave a Comment