Search code examples
javascripthtmlcssgetboundingclientrect

getBoundingClientRect().x of lastChild


my current code working perfectly:

CSS:

#center
{
    background:#781111;
    color:#fff;
    position:absolute;
    left:50%;
    margin-left:-50px;
    width:100px;
}

#c
{
    position:absolute;
    right:0;
    background:yellow;
    color:#781111;
    width:10px;
}

HTML:

<div id="center">
    <div id="a">a</div>
    <div id="a">b</div>
    <div id="c">c</div>
    &nbsp;
</div>

Javascript:

alert(document.getElementById('center').getBoundingClientRect().x);

Now, Up until this point everything working perfectly but when I try to fetch the lastChild (div#c) like this:

alert(document.getElementById('center').lastChild.getBoundingClientRect().x);

It's not working properly.

Here is my jsFiddle: http://jsfiddle.net/hezi_gangina/3m2n9otr/


Solution

  • To get the last children element you should use lastElementChild and to get the x position of BoundingClientRect get left property like:

    var xLastChild = document.getElementById('center').lastElementChild.getBoundingClientRect().left;
    

    http://jsfiddle.net/Pik_at/3m2n9otr/5/