Given the x, y coordinate, I need to find all the html elements below it

I am creating an application where I constantly need to get lists of html elements located in a specific place (x, y relative to the viewport, for example). I consider the following approaches, but none of them satisfy:

(1) Go through html, create a data structure that tracks the x, y position of each element (x, y → a set of elements), and then refers to that data structure when I need to do a search. Unfortunately, this approach is a bit cumbersome, and I'm looking for a better way to solve this problem. Plus, I'm afraid this might be too slow.

(2) Probably the best approach I'm considering is to temporarily add a top-level event handler that captures all hover events, fake the mouse at a specific position, and then remove the handler, but it looks (for example, if there is a bunch absolute div positions in a specific place, I think that it will return only the one that has the highest z index, whereas I need everything, although I'm not sure).

(3) For IE there is a component FromPoint (x, y), but I can not find the equivalent in another browser - this, and it returns only the topmost element.

Please note that the application is built as a bookmarklet, and I do not control the basic html - this, unfortunately, reduces any simple server solutions.

I am ready to use libraries (currently in jquery).

FYI, so far the best I've found here is Obtaining a DIV identifier based on x and y positions ; I wonder if there is something more modern.

+5
javascript html position
Aug 14 '09 at 23:27
source share
1 answer

You are elementFromPoint looking for the elementFromPoint method that exists in MSIE, FF3 +, and in some form in Safari and Opera. It might also be worth getBoundingClientRect look at getBoundingClientRect . Combine the two and you must be in business.

You can also speed up approach # 1 by saving the calculated structure between searches and only recounting it when the page really changes. See how Sizzle in paticular caches their searches and ends the cache when the DOM changes.

This may seem far-fetched, but calculating each item position is what drag and drop handlers have done so far. There are a dozen free ones that correctly optimized this stuff (I suspect YUI will have the most readable code). They may be outdated or try to support browsers that you don't need / should.

+1
Aug 15 '09 at 0:52
source share



All Articles