2

I want to get the total offSetTop and the total offSetLeft of a child element which have many level of parent element and may be adding up.

Is that any shorthand way, besides of adding one by one in manual ways?

Kent Liau
  • 915
  • 15
  • 26

3 Answers3

14

To provide an answer without jQuery:

var a = Element, b = 0, c = 0;
while (a) {
    b += a.offsetLeft;
    c += a.offsetTop;
    a = a.offsetParent;
}

Where Element is your Element node for which you need an offsetLeft and offsetTop.

Micah Henning
  • 2,125
  • 1
  • 18
  • 26
  • works good :) but for me, `c += a.offsetTop - a.scrollTop;` yields correct position just in case that some parents has scrolled. – Miron Aug 31 '20 at 11:17
3

https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect

If you need the bounding rectangle relative to the top-left corner of the document, just add the current scrolling position to the top and left properties (these can be obtained using window.scrollX and window.scrollY) to get a bounding rectangle which is independent from the current scrolling position.

let { left, top } = domNode.getBoundingClientRect();
left += window.scrollX;
top += window.scrollY;
Seph Reed
  • 8,797
  • 11
  • 60
  • 125
3

using jQuery: $( node ).offset() then .top and .left