Raizeo
Raizeo

Reputation: 13

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.

Upvotes: 1

Views: 857

Answers (3)

Rubber Telly Media
Rubber Telly Media

Reputation: 31

I tried parent.document.getElementById("someId"); inside the iFrame's document, but got 'null', until I set both ID and Title on the iFrame to something in the parent Document.

Upvotes: 0

wannadream
wannadream

Reputation: 1760

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

Upvotes: 2

peter bray
peter bray

Reputation: 1345

Add an id to the iframe and then:

document.getElementById("id_of_iframe").getElementById("btn");

Upvotes: 0

Related Questions