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?

1

3 Answers 3

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.

1
  • works good :) but for me, c += a.offsetTop - a.scrollTop; yields correct position just in case that some parents has scrolled.
    – Miron
    Aug 31, 2020 at 11:17
3

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

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;

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.