Skip to the solution
MediumFrontendAsked in 20246 min read

DOM offset absolute coordinate

1.4k views

The problem

Problem, as an interviewer would state it: "Write a function that computes an element's ABSOLUTE position on the page — relative to the whole document, not just its immediate parent — by walking up its offsetParent chain."

Examples:

Code
getAbsoluteOffset(deeplyNestedElement); // { top: 340, left: 120 }, relative to the document

Clarifying questions expected:

  • Is element.offsetTop/offsetLeft relative to the element's immediate offsetParent, or already relative to the document?
  • Does the chain terminate at document.body, or could offsetParent be null earlier for a positioned or hidden element?
  • Would getBoundingClientRect() be a simpler, real alternative — and if so, why walk the offsetParent chain manually at all?

Code / implementation expected: Yes — real, direct proof of the summing algorithm against a deliberately multi-level nested chain, producing the exact correct combined coordinate.

  • js-coding
  • utility
  • algorithm

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: the offsetParent-chain accumulation algorithm produces the exact correct summed coordinate for a deliberately nested 3-level chain

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 78 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

Merge sorted arrays

Continue