javascriptiframe

getElementById outside of iframe


I have a problem when trying to reference an ID outside of a pre-loaded iframe. I would like to know if it's possible to reference an ID that's on a page that the iframe is loaded on, for example:

<html>
<body>
    <div id="username">Guest</div>
    <iframe src="/file.html">
</body>
</html>

Inside of file.html, there's a simple script to try and check what the innerHTML of 'username' is:

<html>
<body>
     <div id="result">Empty</div>
     <button id="btn" type="button">Click</button>
     <script>
        document.getElementById('btn').onclick = function() {
            document.getElementById('result').innerHTML = document.getElementById('username').innerHTML;
        }    
     </script>
</body>
</html>

Tried a few different methods already, but none of them work. I'd appreciate the help in working this out, or at least knowing if it's possible or not.


Solution

  • Use window.parent.document.getElementById() in iframe to interact with parent document.