Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. Web APIs
  3. Document
  4. elementFromPoint()

Document: elementFromPoint() method

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

TheelementFromPoint()method, available on theDocument object, returns the topmostElement at the specified coordinates(relative to the viewport).

If the element at the specified point belongs to another document (for example, thedocument of an<iframe>), that document's parent element is returned(the<iframe> itself). If the element at the given point is anonymousor XBL generated content, such as a textbox's scroll bars, then the first non-anonymousancestor element (for example, the textbox) is returned.

Elements withpointer-events set tonone will be ignored,and the element below it will be returned.

If the method is run on another document (like an<iframe>'ssubdocument), the coordinates are relative to the document where the method is beingcalled.

If the specified point is outside the visible bounds of the document or eithercoordinate is negative, the result isnull.

If you need to find the specific position inside the element, useDocument.caretPositionFromPoint().

Syntax

js
elementFromPoint(x, y)

Parameters

x

The horizontal coordinate of a point, relative to the left edge of the currentviewport.

y

The vertical coordinate of a point, relative to the top edge of the currentviewport.

Return value

The topmostElement object located at the specified coordinates.

Examples

This example creates two buttons which let you set the current color of the paragraphelement located under the coordinates(2, 2).

HTML

html
<p>Some text here</p><button>Blue</button><button>Red</button>

The HTML provides the paragraph whose color will be affected, as well as two buttons:one to change the color to blue, and another to change the color to red.

JavaScript

js
function changeColor(newColor) {  const elem = document.elementFromPoint(2, 2);  elem.style.color = newColor;}document.querySelectorAll("button").forEach((button) => {  button.addEventListener("click", (event) => {    changeColor(event.target.textContent.toLowerCase());  });});

ThechangeColor() method obtains the element located at the specifiedpoint, then sets that element's current foregroundcolor property to thecolor specified by thenewColor parameter.

Result

Specifications

Specification
CSSOM View Module
# dom-document-elementfrompoint

Browser compatibility

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2026 Movatter.jp