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.
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With