Reputation: 269
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:
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:
intersection-observer
to observer visible elements on screen first, then we only need to check in these elements.top
ascendingbottom
ascendingleft
ascendingtop
ascendingAnd 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
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