Checking to see if a frame exists with jQuery

javascript, jquery

Solution

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

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

In your case I think you want to :

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

Why check the length property?

Because if you pass a selector to jQuery that doesn't match anything, the returned result is a jQuery object, is not a falsy value (null, undefined, 0 or false), in an if statement the condition is evaluated to bool, and a non 'falsy' value is evaluated always 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 boolean equivalent, what the if statement does behind the scenes...

Edit: Looking at your frameset markup, and assuming that you want to check if the header frame exists from the main page, you can easily do it by :

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

Or simply:

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

Check this example:

- Frameset Page

- Main Page

Problem

I have found I can do the following: ``` if($('#notice', parent.frames['header'].document).length>0) { alert("It is here!"); } ``` to check for an item in another frame. Is there a way to find out of the frame exists? Specifically I am looking to see if parent.frames['header'].document is there. Is there a reliable way of doing this? Update: Here's 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'm trying to make sure that I can access a div that lives inside of "header". The downside is that, in some cases, main is replaced with another frameset.

Original source