Reputation: 11885
I am doing a research project, the idea is to scan a rendered webpage for elements to calculate their content & layout with other DOM areas.
Basically I need to scan the visible page from upper-left corner to bottom-down.
Given an known element, it is easy to get its position like .offsetLeft
, offsetTop
, or jQuery's .position()
, .offset()
. But how about reverse?
Is thre a function like getElementsByPosition(x, y)
possible in Javascript with a modern browser?
Upvotes: 0
Views: 141
Reputation: 5850
You might want to take a look at document.elementFromPoint(x,y)
, it returns the topmost element at a given point (unless you exclude it from being a target through, e.g. pointer-events
).
As for the cross-browser compatibility, it is quite ok, but you have to be careful if you want to support older browsers, because Safari 4.0 and Opera 10.10 used the wrong coordinates (they wanted the absolute coordinates, as opposed to the relative).
A drawback of this method for your project is that it is relative to the viewport, and returns null
if you check for something which is not currently visible. From the W3C specs:
The elementFromPoint(x, y) method must follow these steps:
If either argument is negative, x is greater than the viewport width excluding the size of a rendered scroll bar (if any), or y is greater than the viewport height excluding the size of a rendered scroll bar (if any), or there is no viewport associated with the document, return null and terminate these steps.
If there is a layout box in the viewport that would be a target for hit testing at coordinates x,y, return the associated element and terminate these steps.
If the document has a root element, return the root element and terminate these steps.
Return null.
Upvotes: 1