Find XY of an HTML element with JavaScript

javascript

To find the x and y coordinates of an HTML element with JavaScript, you can use the offsetTop and offsetLeft properties of the element.

The offsetTop property returns the distance of the element’s top edge from the top edge of the nearest ancestor element that has a position value other than static, while the offsetLeft property returns the distance of the element’s left edge from the left edge of the nearest ancestor element that has a position value other than static.

Here is an example of how you can use these properties to find the x and y coordinates of an element:

const element = document.getElementById('my-element');
const x = element.offsetLeft;
const y = element.offsetTop;
console.log(`Element is at ${x}, ${y}`);

Keep in mind that these properties return the position of the element relative to its nearest ancestor element with a non-static position, not relative to the whole document. If you want to find the position of the element relative to the document, you will need to account for the positions of all of the element’s ancestor elements.

Here is an example of how you can find the absolute x and y coordinates of an element relative to the document:

function getElementPosition(element) {
  let x = 0;
  let y = 0;
  while (element) {
    x += element.offsetLeft - element.scrollLeft + element.clientLeft;
    y += element.offsetTop - element.scrollTop + element.clientTop;
    element = element.offsetParent;
  }
  return { x, y };
}

const element = document.getElementById('my-element');
const position = getElementPosition(element);
console.log(`Element is at ${position.x}, ${position.y}`);

This function uses a loop to traverse the element’s ancestors and add up their positions to find the absolute x and y coordinates of the element.