# doc.elementFromPoint()

[🔰 JS](https://lochiwei.gitbook.io/web/js) ⟩ [browser](https://lochiwei.gitbook.io/web/browser) ⟩ [DOM](https://lochiwei.gitbook.io/web/browser/dom) ⟩ [types](https://lochiwei.gitbook.io/web/browser/dom/type) ⟩ [Document](https://lochiwei.gitbook.io/web/browser/dom/type/document) ⟩ [methods](https://lochiwei.gitbook.io/web/browser/dom/type/document/methods) ⟩ .elementFromPoint

{% hint style="success" %}
returns the <mark style="color:yellow;">**innermost**</mark> (most deeply nested) and <mark style="color:yellow;">**topmost**</mark> (highest CSS <mark style="color:purple;">z-index</mark>) [element](https://lochiwei.gitbook.io/web/browser/dom/type/element) at that point (<mark style="color:red;">**relative to the**</mark> [viewport](https://lochiwei.gitbook.io/web/browser/dom/type/window/viewport "mention")).
{% endhint %}

{% tabs %}
{% tab title="⭐️ 重點" %}
{% hint style="info" %}
the coordinates are <mark style="color:yellow;">**relative**</mark> to the [viewport](https://lochiwei.gitbook.io/web/browser/dom/type/window/viewport "mention").
{% endhint %}

{% hint style="danger" %}
returns <mark style="color:purple;">**null**</mark> if the point is <mark style="color:red;">**out of**</mark> [viewport](https://lochiwei.gitbook.io/web/browser/dom/type/window/viewport "mention").
{% endhint %}
{% endtab %}

{% tab title="💈範例" %}
:floppy\_disk: replit: [document.elementFromPoint()](https://replit.com/@pegasusroe/documentelementFromPoint#script.js)

```javascript
// viewport
const viewport = {
    
    // .width, .height
    width : window.innerWidth,
    height: window.innerHeight,

    // .center
    get center() {
        const x = this.width / 2;
        const y = this.height / 2;
        return {
            x: x, y: y,        // `.center` as object {x:y:}
            coords: [x, y],    // `.center.coords` as array [x,y]
        }
    },
};

// select element at the center of the viewport
let elem = document.elementFromPoint(...viewport.center.coords);
elem.style.background = "red";
```

{% endtab %}

{% tab title="📘 手冊" %}

* [..](https://lochiwei.gitbook.io/web/browser/dom/type/document "mention") ⟩ [.elementFromPoint()](https://developer.mozilla.org/en-US/docs/Web/API/Document/elementFromPoint)
  {% endtab %}

{% tab title="📗 參考" %}

* [ ] JS.info ⟩ [elementFromPoint(x, y)](https://tr.javascript.info/coordinates#elementFromPoint)
  {% endtab %}

{% tab title="👥 相關" %}

* [element](https://lochiwei.gitbook.io/web/browser/dom/type/element "mention")
* coordinates relative to [viewport](https://lochiwei.gitbook.io/web/browser/dom/type/window/viewport "mention").
  {% endtab %}
  {% endtabs %}
