Retrieve the position (XY) of an HTML element

Learn how to retrieve the position (XY) of an HTML element using JavaScript?
Submitted by Shahnail Khan, on April 01, 2022

At times there's a need to know the exact position of an element in HTML to make our websites responsive. The position refers to x & y coordinates. We can find the coordinates of an element at the top-left point in a document using JavaScript.

Let's say, the coordinate of an element is (25,6). Here, X=25 represents the horizontal position and Y=6 represents the vertical position.

We use XY.getBoundingClientRect() method in JavaScript to retrieve the position (XY) of an HTML element.


<!DOCTYPE html>
      <!-- JavaScript code to retrieve position of an element -->
         function Position(XY) {
             var pos = XY.getBoundingClientRect();
             document.getElementById('container').innerHTML ='X= ' + pos.x + ', ' + 'Y= ' + pos.y

      display: flex;
      align-items: center;

      <div id="container"></div>
      <h2 class="click" onclick="Position(this)">IncludeHelp</h2>
      <nav class="topics" onclick="Position(this)">
         <a href="#">HTML</a>
         <a href="#">CSS</a>
      <img src=""


Retrieve the position (XY)

We can get the position of each element in the div container by clicking on a particular element in the output. For example, I clicked on the image and you can see its position is displayed at the top (X=8, Y=93.42500305175781).

JavaScript Examples »


Comments and Discussions!


Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.