Johnny Red
Johnny Red

Reputation: 131

Get position of an element relatively to one ancestor in Javascript

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="/">&nbsp;</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?

Upvotes: 3

Views: 2496

Answers (2)

dollseb
dollseb

Reputation: 327

Use 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

Upvotes: 6

Christophe
Christophe

Reputation: 28174

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.

Upvotes: 3

Related Questions