6

I want to find out the position of an element which is in iframe. I am trying ot use:-

//Function to find the position of element on page
function getElementPosition(elem){
  var posX = 0;
  var posY = 0;
  while(elem!= null){  
        posX += elem.offsetLeft;  
        posY += elem.offsetTop;  
        elem = elem.offsetParent;
    console.log("In function:" + elem.tagName + " " + posX + " " + posY);
  }                              
 return { x : posX, y : posY };  
}

To get the list of all elements of iframe,

var doc1 = $('#page1').get(0).contentDocument; // page1 is id of iframe element
var list1 = doc1.getElementsByTagName('*');
console.log(list1.length);                     // Printing correctly
var index = prompt("Enter element index");
var elem1 = list1[index];
var pos1 = getElementPosition(elem1);
console.log("Positions:" + pos1.x + " " + pos1.y);

But this is not working. Initially elem is not null but elem.offsetParent is null in every case. Am i doing some wrong ?

For some elements, it is working fine. But for some elements, offsetParent is coming null and so their offsetLeft is 0 and offetTop is 0.

Is there any other way to find out position of each element.

Thanks in advance..

Sachin Jain
  • 21,353
  • 33
  • 103
  • 168
  • maybe http://stackoverflow.com/questions/306305/what-would-make-offsetparent-null can help you – Jerome Cance Jun 05 '12 at 08:40
  • 3
    You can access an Iframe only if it is from your own domain - Same Origin Policy restricts the access to Iframe from other domains. – Christoph Jun 05 '12 at 08:40
  • @Christoph Page is on my disk only..So no question about Same Origin Policy – Sachin Jain Jun 05 '12 at 08:42
  • 2
    @blunderboy chrome & ff treat local html resources as cross-domain. So there still might be a "same origin" issue here. – Nir Levy Jun 05 '12 at 09:06
  • @Nir Levy thanks a lot for mentioning about cross-domain policy. But this is not a problem now. Because you can see i have fetched all the elements from the document. – Sachin Jain Jun 05 '12 at 09:24
  • i think it may depending on box model, if block don't have a parent with position other than static offsetParent will be empty – Alexander Jun 05 '12 at 09:35
  • @Alexander I think you are right. But apart from this, then there should be some method by which we can find out the position of a DOM element. – Sachin Jain Jun 05 '12 at 09:48
  • 1
    you are aware, of course, that offsetParent is only available for visible elements and elements that their parent(s) are visible as well. http://stackoverflow.com/questions/5357954/offsetparent-in-jquery-not-returning-expected-relative-positioned-ancestor – Nir Levy Jun 05 '12 at 12:24

1 Answers1

0

You already appear to be using jQuery. Why not let jQuery do the heavy lifting for you?

http://api.jquery.com/position/

http://api.jquery.com/offset/

ray
  • 26,557
  • 5
  • 28
  • 27