How to get the offset position of an element relative to its parent in JavaScript

published: 17 Apr 2022

2 min read

Get the offset position of an element relative to its parent in JavaScript

To get the offset position of an HTML element relative to its parent, you can use the offsetLeft and offsetTop properties of the element.

Here is example:

const div = document.querySelector('.pizza');

console.log('Offset Position: (${div.offsetTop}, ${div.offsetLeft})');

The above example prints the top-left coordinates of an element relative to its parent pixels. By default, the top left corner of the element is (0, 0). The scrollLeft and scrollTop properties are relative to the default coordinate.

How to get the offset position of an element relative to its parent in JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, programming
Check out what's on in the tag: javascript, programming