Run JQuery in the context of another frame

The jQuery function, which you more commonly call with $, takes a second argument called context, which is “which DOM element of jQuery object should I do the search in”. Most of the time you omit this argument, so the context defaults to the current HTML document. When your code is executing in the iframe, the document defaults to that iframe’s document. But you can easily grab the document for one of the other frames.

For example, put this in myFrame.html, and this will remove all the h1 elements from the frame with blah.html in it. Notice the second argument to $, which is the expression that grabs the blah frame from within important frame:

<html>
  <head>
    <script type="text/javascript" src="https://stackoverflow.com/javascripts/jquery.js"></script>
    <script type="text/javascript">
      function doIt() {
        $('h1', window.parent.frames[0].document).remove()
      }
    </script>
  </head>
  <body>
    <h1>My Frame</h1>
    <a href="#" onclick="doIt()">Do It</a>
  </body>
</html>

Leave a Comment