Tip: Element at a specific point on the page

JavaScript, Browser · Dec 18, 2022

Figuring out where an element is located on the page with JavaScript can be tricky. Such needs often arise when working with pointer events or other forms of user input. As expected, such a common problem has many different viable solutions using well-established web APIs.

As I recently discovered, Document.elementFromPoint() provides a pretty interesting and straightforward solution. It allows you to get the element at a specific point on the page and it also works quite well with iframes, too. Additionally, Document.elementsFromPoint() provides similar functionality, but returns an array of all the elements at a specific point on the page, in order of their z-index.

// Returns the topmost element at the specified coordinates
const element = document.elementFromPoint(x, y);

// Returns an array of all the elements at the specified coordinates
const elements = document.elementsFromPoint(x, y);

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub or Twitter.

More like this

  • Tips & Tricks

    Snippet collection

    A collection of quick tips and tricks to level up your coding skills one step at a time.

  • Finds all the ancestors of an element up until the element matched by the specified selector.

  • Handle click outside

    JavaScript, Browser

    Runs the callback whenever the user clicks outside of the specified element.

  • Get element ancestors

    JavaScript, Browser

    Returns all the ancestors of an element from the document root to the given element.