-1

I want get the the position (screen coordinates) of all divs in an iframe using javascript. No jQuery.

I can get all the divs in an array like this:

var arr = window.frames[0].document.getElementsByTagName("div");

Then i tried to do:

var arr = window.frames[0].document.getElementsByTagName("div").x;

But it didn't work. Console logs undefined. Any ideas?

Koiski
  • 568
  • 2
  • 8
  • 23

2 Answers2

2

Try with this:

var divs = window.frames[0].document.getElementsByTagName("div")
    i = 0, rects = [];
for (; i < divs.length; i++)
    rects.push(divs[i].getBoundingClientRect());

Now the array rects contains objects that define the position relative to the viewport of all your divs. Each of the elements will be something like this:

{
    top: ...,
    right: ...,
    bottom: ...,
    left: ...,
    width: ...,
    height: ...
}

Those properties are the number of pixel from each border (or the width or height).

IE6-8 don't report the width and height properties, though, but it's easy to compute them.

MaxArt
  • 22,200
  • 10
  • 82
  • 81
1

getElementsByTagName returns an array. The array object has no x property.

You will need to iterate over the members, collecting each value of x.

Furthermore (as pointed out in comments below), divs don't have an x property. See the question "Retrieve the position (X,Y) of an HTML element" for details on how to manage that.

Community
  • 1
  • 1
Paul Butcher
  • 6,902
  • 28
  • 39