5

Our dev and corporate sites have a slightly different frame hierarchy.

Very occasionally I need to reference an element in a different frame.

Unfortunately, I don't know where that frame will be in the hierarchy. I do however know it's id.

How can I find a frame or the specific element, when I don't know the exact structure?

For clarification In dev, it's basically just a page, containing a frame. I'm in the context of the frame, and was just using window.top.document to get the document I wanted.

In prod, the nesting is different, window.top.document doesn't work, as it is inside of two other frames.

I can't change this structure, it's just how our application portal works.

CaffGeek
  • 21,856
  • 17
  • 100
  • 184

4 Answers4

6

If the iframe is from the same domain, the elements are easily accessible via jQuery as

$("#frameID").contents().find("#elementID").hide();

There are a few exceptions Here about foreign domain:

Community
  • 1
  • 1
Maziar Barzi
  • 436
  • 5
  • 9
3

maybe you could try traversing all the frames. you will either need to use a breadth-first or depth-first search depending on how deep the frame nesting will be. pass it the root originally.

frameSearch(yourElementId,$("frame"));

function frameSearch(elementId,frames){
      if (!(frames)) {return "element not found";}
      $.each(frames,function(){
           var $elementFound = this.find("#"+elementId);
           if ($elementFound){
               return $elementFound;
           }
           var newFrames = this.find("frame");
           if (newFrames) {frameSearch(elementId,newFrames);}
      });
}

I'm not 100% sure of the correctness of this recursive algorithm but this is the right idea I believe.

EDIT:

if you need to find the topmost parent, try:

 var $currentDocument = $("document");
    while ($currentDocument.parent()){
         if ($currentDocument.find("#"+yourElementId)){
              $yourElement = $currentDocument.find("#"+yourElementId);
              break;
         }
         $currentDocument = $currentDocument.parent();
    }

    if (!($yourELement)){
        $yourElement = frameSearch(yourElementId,$("frame"));
    }

this will check upwards first, then downwards if that doesn't work

Evan
  • 5,975
  • 8
  • 34
  • 63
0

this worked for me...

USERNAME='input#username';

    frame_count=window.parent.frames.length;
    for(f=0;f<frame_count-1;f++){
        test_frame=window.parent.frames[f].document.body;
        if ( $(USERNAME, test_frame).length==1 ) {
            INPUT_FRAME=f;
            break;
        };
    };

detail_frame=window.parent.frames[INPUT_FRAME].document.body;

$(USERNAME, detail_frame).val(username);
Mohclips
  • 1
  • 1
0

If you know the id of the frame you can just use id selector and contents() method to find the elements within the iframe. Try this

$("#iframeId").contents().find("elementToFind")
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124