jQuery position() in Pure Javascript

jQuery's position() method gives the top-left position of the element relative to its offset parent element.

Offset parent is different from the direct parent element. Offset parent is the closest parent that has the CSS position: relative or position: absolute. If such a positioned element does not exist then the closest <td>, <th>, <table> or the <body> becomes the offset parent.

Native Javascript has 2 equivalent properties :

  • offsetTop : This gives the distance between an element and the top edge of its offset parent
  • offsetLeft : This gives the distance between the element and the left edge of its offset parent

Using these 2 properties we can get the equivalent of jQuery's position() method :

var element = document.querySelector("#container");

var position = { 
                top: element.offsetTop, 
                left: element.offsetLeft, 
            };

console.log(position);
jQuery offset() in Pure Javascript