What is the most optimized method to select all HTML Elements existing in an specific area?

60 views Asked by At

Is there any optimized way to select all DOM elements inside a rectangle?

To make the situation more clear I've brought some illustrations. Imagine we have an HTML page like this:

page

Now we're gonna select elements based on a specific rectangle.

const ourBox = {
    offsetTop: 1100,
    offsetLeft: 600,
    width: 400,
    height: 400
}

const elements = getAllElementsInsideBox(ourBox)

console.log(elements)
// Logs array of elements which have collisions with imagined box

page+rect

For the above box, selected elements will be the elements which are specified with blue border as it can be seen in the picture:

page+rect+selected

Bonus Challenge

If it's not that hard to find the optimized code for rectangle, let's make it more challenging by selecting elements inside a circle. The code will be like:

const ourCircle = {
    centerTop: 1200,
    centerLeft: 500,
    radius: 150
}

const elements = getAllElementsInsideCircle(ourCircle)

console.log(elements)
// Logs array of elements which have collisions with the imagined circle

page+circle

This is a challenge for me and I'm working on it. If I found the best solution I will share with you here, also I'll be appreciated if you share your solution with me.

Note: Checking all elements offsets one by one is a way, but maybe not that optimized! let's try in different ways.

0

There are 0 answers