Without a framework, determining the position of a DOM element can be tricky, as this element can be absolutely positioned, or embedded in another element with its own offset.

Write a function to traverse the element's parents all the way to the document root, and add up the top and left offset values, as a very basic implementation.

function MyPosX(node,x){
  if (node.parentNode==document.body) return node.offsetLeft;
  return x+MyPosX(node.parentNode.offsetLeft,x);


Please double check the parent pointers and boundary conditions. The above code is for illustration only.


querySelectorAll returns a non-live NodeList, therefore, to really select the element that you need, you must include an index like so:

var d = document.querySelectorAll('#a1')[0]; //assuming that there is an element with this ID

It would be much easier to just use document.getElementById("a1") in this case though.

var d = document.getElementById("a1");

More info on getElementById

Potential duplicate question

Related Query

More Query from same tag