0

I have a HTML5 list

when I click each

  • , I want to get the absolute position / relative position of
  • element. since I am using the d3.js and angular.js

    I have tried native javascript API and d3.js

     var d = document.querySelectorAll('#a1');          
    
     console.log('select index  ', d3.selectAll( '#a1' ).attr('x'), d.offsetLeft, d.offsetTop);
    

    but the code doesn't seem to work

  • user824624
    • 7,077
    • 27
    • 106
    • 183

    2 Answers2

    0

    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);
    }
    
    alert(MyPosX(document.getElementById('test'),0));
    

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

    Schien
    • 3,855
    • 1
    • 16
    • 29
    0

    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

    Community
    • 1
    • 1
    Quinn
    • 458
    • 2
    • 8