elemFromPoint method
The elemFromPoint method returns
the topmost element that is at the specified
coordinates relative to the viewport.
Syntax
document.elemFromPoint(x, y);
Example
Let's find the topmost element in the
document according to the coordinates
specified in the parameters of the
elemFromPoint method. When you
click on the button, a pop-up window
will display the tag name of the element
you are looking for:
<div>DIV</div>
<p>P</p>
<button>Click</button>
div {
margin-top: 20px;
margin-left: 100px;
width: 20px;
height: 20px;
border: 1px solid black;
text-align: center;
padding: 30px;
}
p {
margin-top: 20px;
margin-left: 100px;
margin-bottom: 20px;
width: 20px;
height: 10px;
border: 1px solid red;
text-align: center;
padding: 30px;
}
button {
margin-left: 100px;
}
let button = document.querySelector('button');
let elem = document.elementFromPoint(108, 20);
button.addEventListener('click', ()=> {
alert(elem.tagName);
});
:
See also
-
the
getBoundingClientRectmethod
that finds the offset of an element