Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Finding an element, regardless of frame

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.

like image 614
CaffGeek Avatar asked Nov 29 '11 18:11

CaffGeek


2 Answers

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:

like image 191
Maziar Barzi Avatar answered Nov 04 '22 16:11

Maziar Barzi


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

like image 32
Evan Avatar answered Nov 04 '22 14:11

Evan