JavaScript offsetTop Property

It returns the top position in pixels, relative to the top of the parent element. It includes the top position, and margin of the element and the top padding, scrollbar, and border of its parent element.

Example: This example shows the use of the above-explained approach.

html




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,
     initial-scale=1.0">
</head>
 
<body>
    <div id="target">
        <p>Click the button</p>
 
 
        <button onclick="getPoint()">
            Click
        </button>
 
        <p id="output"></p>
 
    </div>
 
    <script>
        function getPoint() {
            let target = document
                .getElementById("target");
 
            let output = document
                .getElementById("output");
 
            output.innerHTML = "offsetTop: "
                + target.offsetTop;
        }
    </script>
</body>
 
</html>


Output: 

find the position of HTML elements in JavaScript

How to find the position of HTML elements in JavaScript ?

In this article, we are given an HTML document and the task is to get the position of any element by using JavaScript. Use the following steps to get the position:

Step 1: Selecting an element: Before finding the position, it is necessary to select the required HTML element. Every element in HTML is structured in a tree-like format known as DOM or Document Object Model. In JavaScript, there is an in-built object called the document object that points to the root of the DOM tree. It means that it is possible to access every component of the web page.
The document object has various methods available to find a particular element within the HTML page. Each of these methods has a parameter that could be used to find the required element. Some of the methods are:

Step 2: Finding the position of the element: To get the location of any HTML element in the (x, y) coordinate format.

There are two document properties that are used:

Table of Content

  • JavaScript offsetTop Property
  • JavaScript offsetLeft Property

Similar Reads

JavaScript offsetTop Property

It returns the top position in pixels, relative to the top of the parent element. It includes the top position, and margin of the element and the top padding, scrollbar, and border of its parent element....

JavaScript offsetLeft Property

...