views:

78

answers:

1

If i want to find all elements that are inside a box region, what is the best way to do it as a Firefox extension? If i check all leave elements and call getBoundingClientRect(), it'd be too slow given that there can easily be more than 500 leaves on a page.

Any help will be appreciated. Thanks.

+1  A: 

You can use document.elementFromPoint and visit each fifth pixel (every fifth is much faster than visiting every single pixel), adding each found element to an array:

function getElementsInRegion(x, y, width, height) {

    var elements = [],
        expando = +new Date,
        cx = x,
        cy = y,
        curEl;

    height = y + height;
    width = x + width;

    while ((cy += 5) < height) {
        cx = x;
        while (cx < width) {
            curEl = document.elementFromPoint(cx, cy);
            if ( curEl && !curEl[expando] ) {
                curEl[expando] = new Number(0);
                elements.push(curEl);
                cx += curEl.offsetWidth;
            } else {
                cx += 5;
            }
        }
    }

    return elements;

}
J-P
Thanks. But are there ways to make document.elementFromPoint return the 2nd topmost elements instead? My addon adds another layer on top, so document.elementFromPoint would return that layer instead.
s.wong
You can temporarily hide your layer (`display:none;`) and then run the function.
J-P
Thanks a lot J-P for the elementFromPoint() I was just looking for this
Mic