Using iframes via frames

A great way to go through all the iframes on a page is by using window.frames. It returns the window itself, which is an array-like object, containing the direct sub-frames of current window.

Example

var frames = window.frames;

for(var i = 0; i < frames.length; i++) {
  frames[i].document.body.style.background = "red";
}

Notes

  • frames is a list of frame objects. It is similar to an array in having a length property which and its items can be accessed using [i] notation.

  • window.frames === window evaluates to true.

  • Each item in window.frames represents the window object corresponding to the given <iframe>‘s content and not the DOM element itself, i.e. window.frames[0] is same as document.getElementsByTagName("iframe")[0].contentWindow.

  • If name attribute is provided to an iframe, it can also be accessed using that name.

    // <iframe name="myIframe"></iframe>
    // The above frame can be accessed using
    // either
    window.frames["myIframe"]
    // or
    window.frames.myIframe
    

Leave a Reply