0

How to get the element's position (left & top) relative to its parent?

Note: the parent position is neither relative nor absolute, so offsetLeft & offsetTop wouldn't work.

The parent/child might have margins/borders/paddings.

Vanilla JS only, no jquery.

Heyyy Marco
  • 633
  • 1
  • 12
  • 22
  • 2
    Does this answer your question? [Element's coordinates relative to its parent](https://stackoverflow.com/questions/26423335/elements-coordinates-relative-to-its-parent) – Sifat Moonjerin May 06 '21 at 06:04
  • No. The solution works only if the parent has no border. If does, the result shifted. – Heyyy Marco May 06 '21 at 07:24

2 Answers2

1

You can use .getBoundingClientRect() which returns position of the element relative to the viewport. So you can get position of both the element and the parent using .getBoundingClientRect() and calculate the elements position relative to parent from it. Check out the following answer.

Element's coordinates relative to its parent

Sifat Moonjerin
  • 180
  • 1
  • 12
  • is that calculates automatically for the parent's margin/border/padding ? – Heyyy Marco May 06 '21 at 06:09
  • It calculates height/width = height/width + padding. Checkout the documentation. [Element.getBoundingClientRect()](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect) – Sifat Moonjerin May 06 '21 at 06:12
  • i tested (clientRect.top - parentRect.top) only works for parent without borders & paddings. The width of borders & paddings shifted the result. Yes i can fetch the border/padding width. Is there a more simple way? – Heyyy Marco May 06 '21 at 06:22
  • update: the child's borders & paddings are shifting the result too – Heyyy Marco May 06 '21 at 06:30
0

You can get the style via window.getComputedStyle and vanilla js selectors.

function getStyleProp(elem, prop){
    if(window.getComputedStyle)
        return window.getComputedStyle(elem, null).getPropertyValue(prop);
    else if(elem.currentStyle) return elem.currentStyle[prop]; //IE
}


elem = document.getElementById("id")
console.log(getStyleProp(elem, "top"))
console.log(getStyleProp(elem, "left"))

Original function written by Rob W

src: Read CSS property of an element using JavaScript

W-B
  • 850
  • 5
  • 16