Files
30-seconds-of-code/blog_posts/js-element-from-point.md
Angelos Chalaris a643b49bf0 Add 2 new articles
2022-11-16 22:54:07 +02:00

1.3 KiB

title, shortTitle, type, tags, expertise, author, cover, excerpt, firstSeen
title shortTitle type tags expertise author cover excerpt firstSeen
Tip: Element at a specific point on the page Element at specific coordinates tip javascript,browser intermediate chalarangelo blog_images/armchair-in-yellow.jpg Using `Document.elementFromPoint()` to easily get the element at a specific point on the page. 2022-12-18T05:00:00-04:00

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 speicifed coordinates
const element = document.elementFromPoint(x, y);

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