The correct approach is to use element.getBoundingClientRect() to Get absolute position of element in JavaScript. Use element id to get its position in the browser window.
How to get Get the absolute position of element JavaScript Example
This function returns an element’s position relative to the whole document (page):
function getOffset(el) {
const rect = el.getBoundingClientRect();
return {
left: rect.left + window.scrollX,
top: rect.top + window.scrollY
};
}
To get the X position
getOffset(element).left
To get the Y position:
getOffset(element).top
Complete HTML Example code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="ptag" style="margin:50px">Hello wrold</p>
<script>
function getOffset(el) {
const rect = el.getBoundingClientRect();
return {
left: rect.left + window.scrollX,
top: rect.top + window.scrollY
};
}
console.log(getOffset(ptag));
</script>
</body>
</html>
Output:
Do comment if you have any doubts and suggestions on this topic. Also, comment if you have any better examples.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version