Get the exact location of an element on Webpage

Get the exact location of an element on Webpage

How to find the exact location of an element on the webpage?

In this blog, I'll explain how to get the location of an element on a web page.

Approach

  1. First find the nearest parent element of the given element
  2. Then get the coordinates of our object/element with respect to the parent object.
  3. Loop these actions until you reach the topmost parent element and add up the relative offsets/coordinates.

This approach gives real-time results that if you resize the window then it will recalculate and give the new pixel position of the element.

Implementation

Pass the element object as a parameter whose location is going to be calculated.

The parent element of this object can be obtained with the help of offsetParent property. To get the relative position of our element with the parent element, the offsetTop and offsetLeft property of our element is used.

A loop will iterate over elements and add up the relative offsets until the topmost element of the element tree is not reached.

This method will give the location of the top-left pixel of an element.

function locatePixel(obj) {
  var curleft = 0,curtop = 0;
  if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
            obj = obj.offsetParent;
        } while (obj);
        console.log(curleft);
        console.log(curtop);
    }
}

Try out this sandbox to get a better understanding

If you find something wrong in this blog then please do let me know in the comments.

Want to connect with me or know about me? Click here

Did you find this article valuable?

Support Build with Yash by becoming a sponsor. Any amount is appreciated!