Get child element distance from parent top <p><a href="https://i.stack.imgur.com/vlROs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vlROs.png" alt="Child distance from top parent"></a></p> <p>Let's say I have an <code>&lt;li&gt;</code> element inside a scrollable div and the scroll was set to show that element in the viewport. </p> <p>I need to get the distance between that element and its scrollable parent, as shown in the picture above, but both <code>element.getBoundingClientRect().top</code> and <code>element.offsetTop</code> give me the wrong values. Can that be done?</p> <p>I made a pen, to make things a little bit easier:</p> <p><a href="http://codepen.io/Darksoulsong/pen/LbYMex" rel="nofollow noreferrer">http://codepen.io/Darksoulsong/pen/LbYMex</a></p> <p>A piece of my code:</p> <pre><code>document.addEventListener("DOMContentLoaded", function(event) { var selectedEl = document.getElementById('consequatur-51'); var selectedElRect = selectedEl.getBoundingClientRect(); var sidebar = document.getElementById('sidebar'); sidebar.scrollTop = selectedEl.offsetTop - 60; document.getElementById('offsetTop').innerText = selectedEl.offsetTop; document.getElementById('rectTop').innerText = selectedElRect.top; }); </code></pre>