How to capture x, y position of html elements using javascript

In my html document there are several div elements with a specific css class and I want to get the x, y position of these elements, thanks in advance.

+6
source share
3 answers

Use getBoundingClientRect : http://ejohn.org/blog/getboundingclientrect-is-awesome/

For instance:

 var div = document.getElementById("yourDiv"); var rect = div.getBoundingClientRect(); alert("Coordinates: " + rect.left + "px, " + rect.top + "px"); 

Remember that getBoundingClientRect gives coordinates relative to the current viewport, which means that if you want to know the coordinates relative to document.body , you need to add horizontal and vertical scroll values ​​( document.documentElement.scrollLeft or document.body.scrollLeft for Firefox and .scrollTop , of course).

+18
source

If I understand, you want to do this http://www.quirksmode.org/js/findpos.html

+1
source

The following are examples of extracting a ClientRect HTML element

 # first tag link of this page document.getElementsByClassName('post-taglist')[0].children[0].getClientRects()[0] # question div document.getElementById('question').getClientRects()[0] 

With it, you have rights to the right, top, top, width, left and bottom attributes.

+1
source

Source: https://habr.com/ru/post/917202/


All Articles