Get element at specified position - JavaScript

JavascriptHtmlDom

Javascript Problem Overview


Using Javascript how can I identify the element at a given position? Basically I'm looking to write a function that takes two input parameters (the x and y coordinates) and returns the html element at the position on the screen represented by the parameters.

Javascript Solutions


Solution 1 - Javascript

Solution 2 - Javascript

You can use the native JavaScript elementFromPoint(x, y) method, that returns the element at coordinates x,y in the viewport.

See the elementFromPoint w3c draft

And, a code sample:

function changeColor(newColor) {
    // Get the element placed at coords (2, 2)
    var elem = document.elementFromPoint(2, 2);
    // Set the foreground color to the element
    elem.style.color = newColor;
}

<p id="para1">Change this text color using the following buttons.</p>
<button onclick="changeColor('blue');">Blue</button>
<button onclick="changeColor('red');">Red</button>

You can use setInterval() to continuously check the element's hover event but it's not recommended, try to use .hover(...) and css instead to enhance the application performance.

Solution 3 - Javascript

To get the topmost element at a specific position relative to the viewport, document.elementFromPoint(x, y) can be used.

To obtain an array of all the elements at a specific position, use document.elementsFromPoint(x, y).

In both cases, x is the horizontal coordinate which is relative to the left of the viewport and y is the vertical coordinate which is relative to the top of the viewport.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkjvView Question on Stackoverflow
Solution 1 - JavascriptrahulView Answer on Stackoverflow
Solution 2 - JavascriptAndrés MoralesView Answer on Stackoverflow
Solution 3 - JavascriptUnmitigatedView Answer on Stackoverflow