Enesy
Enesy

Reputation: 269

What's best (fastest) way to get DOM elements in specific area

I want to get all DOM elements within a selector area (created when press and drag left mouse, like photoshop, illustrator, figma selector). as the following img: enter image description here

enter image description here

All elements are absolute position with left, top, width, height attributes. And the selector given a rectangle with left, top, bottom, right, width, height. And please note that we have alot of elements (e.g: 10,000 DOM elements), so if we loop through all 10,000 elements to check if it with in selector area, that's not good idea.

I've tried 2 solutions:

  1. Using intersection-observer to observer visible elements on screen first, then we only need to check in these elements.
  2. Cache all elements with 4 objects:
    • byTops: store all elements with order top ascending
    • byBottoms: store all elements with order bottom ascending
    • byLefts: store all elements with order left ascending
    • byRights: store all elements with order top ascending

And when we check, it maybe faster

And this is DEMO for solution 1: Demo for solution 1

Does anyone have a better solution for this scene? Please help me!

thanks you very much!

Upvotes: 2

Views: 395

Answers (1)

dave
dave

Reputation: 64667

If you know the minimum size of each element they can select, you could potentially use document.elementFromPoint to get the elements selected.

What I mean is, say they drew a selection, and each thing they can select is at least 40px x 60px. You could then do something like:

let {top, left, right, bottom} = rectangleCoords;
const selectedElements = new Set();
for (let x = left; x <= right; x += 40) {
    for (let y = top; y <= bottom; y+= 60) {
        const el = document.elementFromPoint(x, y).closest('.thing-you-want');
        if (el) {
            selectedElements.add(el);
        }
    }
}

Upvotes: 1

Related Questions