How to find how many pixels down a div relative to a parent div (jquery)

To give an example, how would I determine how many pixels a parent has child3?

<div class="parent" id="unique"> <div class="child1"></div> <div class="child2"></div> <div class="child3"></div> <div class="child4"></div> </div> 

Suppose classes define width, height, padding, margins, etc.

+4
source share
3 answers
 var child=$('.child3'); var parent=$('.parent'); return child.offset().top-parent.offset().top; 

Offset determines the position of the element relative to the document.

+2
source

You can use .offset() :

 var $child = $('.child3'); var offset = $child.parent().offset().top - $child.offset().top; 

I'm not too sure that it takes into account borders and fields, but they are not difficult to take into account.

+2
source

I believe that you are looking for the position() function. It returns an object containing the values โ€‹โ€‹of top and left .

Description Get the current coordinates of the first element in the set of matched elements relative to the offset parent.

Documentation for position()

0
source

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


All Articles