Javascript – How to get top (as in locale) attribute of a DIV element using Javascript

cssdomjavascript

I have a group DIV tags in an HTML page whose location is controlled via several parent/grandparent DIVs. Those parent and grandparent's location is controlled via CSS classes. I need to retrieve the top attribute of the given DIV. Where is it in the DOM or how would I calculate it using Javascript?


Clarification: I need the coordinate value of the top of the DIV object in absolute terms (relative to the window).

Best Answer

Since offsetTop and offsetLeft give you relative position values, you can get the absolute values by traversing up the tree of offsetParents, aggregating the offsetTop and offsetLeft values of each parent element:

function findPos(obj) {
  var curleft = curtop = 0;
  if (obj.offsetParent) {
    do {
      curleft += obj.offsetLeft;
      curtop += obj.offsetTop;
    } while (obj = obj.offsetParent);
    return [curleft,curtop];
  }
}

More detailed information: JavaScript Find position