Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find position of an element relative to latest relative positioned parent with javascript

Is There any way to find an element position related to latest relative position parent?

I want a javascript way

assume we have this HTML

<div id="div1" style="position:relative"> 
   <div id="div2" style="padding:10px">
      <div id="div3" style="position:absolute top:15px; left:20px;">Stack</div>
   </div>
</div>

I want position of "div3" related to "div1".

Thanks

like image 949
Mosijava Avatar asked Feb 26 '12 15:02

Mosijava


People also ask

How do I find relative position to parents?

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.

What is getBoundingClientRect relative to?

getBoundingClientRect() gives a result relative to the viewport's top-left corner ( 0,0 ), not relative to an element's parent, whereas el.

What is JavaScript offsetLeft?

The offsetLeft property returns the left position (in pixels) relative to the parent. The returned value includes: the left position, and margin of the element. the left padding, scrollbar and border of the parent.

How do you know the position of an element?

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found. The following illustrates the syntax of the indexOf() method.


1 Answers

div3.offsetTop and div3.offsetLeft should fit your requirement(s).

like image 84
Alex Avatar answered Oct 25 '22 11:10

Alex