How to detect if an element is under another element? (HTML, via javascript)

Asked

Viewed 340 times

1

I would like to know how to detect, in a simple way and return the information I need, if one element is under the other. I’ve tried for the offset, but it was very difficult and did not result in almost anything,...

For example:

p{background:red}
.teste{margin-left: -20px}
button{position: relative; top:-35px}
<p>Elemento 0</p>
<button>Elemento 1</button><button class="teste">Elemento 2</button>

Note that "element 2" is over "element 1", and both are over "element 0".

I wanted a role in which I send the element 2 and she returns the elements 1 and 0, that is, elements that are graphically below element 1.

  • 1

    If you can revise your question, you are confused in this passage: "I wanted a function where I send element 2 and it returns elements 1 and 0,..." .. you want to send element 2 to where?

1 answer

1

You can use the function getBoundingClientRect, it basically returns both the position of the element and its size. With this information only do the checking of the other elements.

One way to do this check to discover the elements below is to iterate over all the elements of the DOM, see how it would look:

function getBelowElements(el) {
    const sourceBounding = el.getBoundingClientRect();
    let belowElements = [];

    for (const currentElement of document.all) {
        const targetBounding = currentElement.getBoundingClientRect();

        // Se todas as condições forem falsas, é porque está tendo uma sobreposição
        if (!(sourceBounding.right < targetBounding.left ||
            sourceBounding.left > targetBounding.right ||
            sourceBounding.bottom < targetBounding.top ||
            sourceBounding.top > targetBounding.bottom)) {
            belowElements = [...belowElements, currentElement]; // Adiciona o elemento atual ao array de elementos sobrepostos
        }
    }

    return belowElements; // Retorna o array de elementos sobrepostos
}

console.log(getBelowElements(document.getElementsByClassName("teste")[0]));
p{background:red}
.teste{margin-left: -20px}
button{position: relative; top:-35px}
<p>Elemento 0</p>
<button>Elemento 1</button><button class="teste">Elemento 2</button>
<button>Elemento 3</button>

This is a little bit costly depending on the amount of elements on your page, but I couldn’t think of a simpler way.

  • Is there any way to limit this search for elements? For example: getBelowElements(a, b) :: Where a is the element I’m looking for and b is the element I want to check if it’s overwriting something. To avoid searching the entire document...

  • @Your comment is not very clear. I recommend that you make an edit and put exactly what you need in your question, it prevents that answers occur that is not exactly what you need.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.