# Get the position of an element relative to the document

Add the scroll offsets to the element’s viewport position.

Canonical: https://1loc.dev/dom/get-the-position-of-an-element-relative-to-the-document/
Version: 1.0.0
Runtime: JavaScript · modern browsers (DOM)
Verification: Usage lines executed in headless Chromium against the fixture markup; no external services
Updated: 2026-10-28

## Implementation

```javascript
function getPosition(element) { const rect = element.getBoundingClientRect(); return { left: rect.left + window.scrollX, top: rect.top + window.scrollY }; }
```

## Usage

Markup:

```html
<div style="height: 1000px"></div>
<p id="target" style="margin: 0 0 0 40px">Target</p>
<div style="height: 2000px"></div>
```

Script:

```javascript
const target = document.querySelector('#target');
getPosition(target); // → { left: 40, top: 1000 }
window.scrollTo(0, 600);
getPosition(target); // → { left: 40, top: 1000 }
target.getBoundingClientRect().top; // → 400
```

Lines marked → were executed in headless Chromium against the markup above, and each result was compared with the value shown. Lines marked e.g. are illustrative.

## Limits

- The original assigned to an undeclared r: a ReferenceError in strict mode and ES modules.
- getBoundingClientRect is relative to the viewport, as the last line shows; adding the scroll offsets gives document coordinates that stay put while scrolling.
- Transforms are included, and values are fractional when layout is.

The function does not validate its arguments. Add checks where it receives untrusted input.

## Source and license

Original: https://github.com/phuocng/1loc/blob/14b481cf60dff1620ab1bb99a43b1f68068cdd9b/contents/get-the-position-of-an-element-relative-to-the-document.mdx
Author: Nguyen Huu Phuoc and original contributors
Contributors: See original repository history
Source commit: 14b481cf60dff1620ab1bb99a43b1f68068cdd9b
Copyright (c) 2020 phuoc-ng
License: MIT — https://1loc.dev/licenses/
Maintainer: Oveyon
Modifications: Declares the rect variable; the original assigned to an undeclared r, which throws in strict mode and ES modules. Executed in Chromium. Original MDX retained as inert source evidence.
