Checking for a frame with jQuery

I found that I can do the following:

if($('#notice', parent.frames['header'].document).length>0) { alert("It is here!"); } 

to check an element in another frame.
Is there any way to find the frame? In particular, I look to see if there is a parent.frames ['header'] file.

Is there a reliable way to do this?

Update: Here is my frameset code:

 <frameset rows="104,*,22" frameborder="NO" border="0" framespacing="0"> <frame src="header.php" id="header" name="header" scrolling="no" title="Header and Menu" noresize> <frame src="main.php" title="Main content" name="main"> <frame src="footer.php" name="footer" title="Footer" scrolling="NO" noresize> </frameset> 

I am trying to make sure that I can access the div that lives inside the "header". The disadvantage is that in some cases, main is replaced with a different set of frames.

+4
source share
2 answers

If you want to know if an element exists, you need to check the length property, see the jQuery FAQ :

 if ($('#myFrame').length) { alert('#myFrame exists'); } 

In your case, I think you want:

 if ($('frame[name=header]', parent).length) { alert('frame exists'); } 

Why check the length property?

Because if you pass a jQuery selector that does not match anything, the returned result is a jQuery object, it is not a false value (null, undefined, 0 or false) in the if statement condition evaluates to bool, and non 'falsy' always evaluates to true:

 if ($('#nonExisting')) { alert('always true'); } // because !!$('#nonExisting') == true; // and !!'hello' == true; !!0 == false; 

I used !! as an example of a simple way of turning any expression into its logical equivalent, which the if statement does behind the scenes ...

Edit: By looking at the layout of the frames and assuming that you want to check if the header frame exists from the main page, you can easily do this:

  if (parent.header !== undefined) { // frame exists } 

Or simply:

  if (parent.header) { // frame exists } 

Check out this example:

+3
source

Check selector:

 if ($("#myFrame").length) alert("It exists!"); 
+1
source

All Articles