Get the position of an element relative to the document

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

JavaScriptBrowser · DOM Version 1.0.0 · MIT · .md

get-the-position-of-an-element-relative-to-the-document.js
function getPosition(element) { const rect = element.getBoundingClientRect(); return { left: rect.left + window.scrollX, top: rect.top + window.scrollY }; }

Usage

Markup

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

Script

usage.js
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.

Know the 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 above is the code the usage lines run. It does not validate its arguments; add checks where it receives untrusted input.

Source & maintenance

Based on Get the position of an element relative to the document from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.

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.

Maintained by Oveyon. Original source commit: 14b481cf60df. This edition’s file: contents/get-the-position-of-an-element-relative-to-the-document.mdx in akamind/1loc, commit 0a77f131b22d. Read the license.

Usage lines executed in headless Chromium against the fixture markup; no external services · reviewed October 28, 2026.

Keep exploring

Type two or more characters. Try “duplicate”, “webhook” or “retry”.