Say I have the following HTML code (it's an example):
<div id="site_header_container" class="site_bar_container">
<div id="site_header">
<div id="header_logo_container">
<a class="sliced" id="header_logo" href="/"> </a>
</div>
</div>
</div>
With several CSS applied. Basically in the div with id="site_header_container"
, there is a background-image
. I would like to know which top and left values the <a>
element has inside the site_header_container
.
So, how can I given one element, call it, ancestor, and another element call it descendant, know the position of descendant relatively to its ancestor in pure Javascript (I don't want to use any libraries) and it has to work just in Chrome?
Say I have the following HTML code (it's an example):
<div id="site_header_container" class="site_bar_container">
<div id="site_header">
<div id="header_logo_container">
<a class="sliced" id="header_logo" href="/"> </a>
</div>
</div>
</div>
With several CSS applied. Basically in the div with id="site_header_container"
, there is a background-image
. I would like to know which top and left values the <a>
element has inside the site_header_container
.
So, how can I given one element, call it, ancestor, and another element call it descendant, know the position of descendant relatively to its ancestor in pure Javascript (I don't want to use any libraries) and it has to work just in Chrome?
Share Improve this question edited Nov 20, 2013 at 22:35 Johnny Red asked Nov 20, 2013 at 21:21 Johnny RedJohnny Red 1311 silver badge10 bronze badges 6- Find the location of each and use MATH. stackoverflow./questions/6255019/… – Diodeus - James MacFarlane Commented Nov 20, 2013 at 21:28
- @Diodeus the OP said no jQuery – Christophe Commented Nov 20, 2013 at 21:30
- How is jQuery not "pure" JavaScript? You mean JavaScript you write entirely yourself? – ithcy Commented Nov 20, 2013 at 21:33
- @ithcy because it's not standardized (cf. promises for example). But I guess the OP meant plain JavaScript (no library dependency). – Christophe Commented Nov 20, 2013 at 21:40
- 1 @Christophe it's just funny, because in order to solve this in a way that works reliably across browsers and layout scenarios, OP must eventually end up with a crippled version of this :) – ithcy Commented Nov 20, 2013 at 21:46
2 Answers
Reset to default 6Use getBoundingClientRect() to reciev the position of the child and parent element and than subtract parent's coordinates from child's.
var coords = element.getBoundingClientRect();
console.log(coords.top, coords.right, coords.bottom, coords.left);
If parents coordienates are (left)500, (top)500 and child's 550, 550, child's coordinates relative to its parent are 50, 50
http://codepen.io/dollseb/pen/oilyH
This page explains how to do it. Starting from your a element, you need to climb up the DOM hierarchy and add the offsetTop
and offsetHeight
properties of each parent until you reach the ancestor.