0

This is main.html

<body>
    <iframe id="frame" src="frame.html"></iframe>
    <script type="text/javascript">
    document.getElementById('frame').contentWindow.document.getElementById('test').innerHtml = 'abcdefgh';
    </script>     
</body>

And this is frame.html

<body>
    <p id="test">0123456798</p>
    <script type="text/javascript"></script>
</body>

Error: Uncaught TypeError: Cannot set property 'innerHTML' of null

Why did not work , AND how can I change id="test" text

Mohammad
  • 21,175
  • 15
  • 55
  • 84
jdio
  • 3
  • 2
  • I think you don't need to use `contentWindow.document`. The code should be like `document.getElementById('frame').getElementById('test').innerHtml` – Mohammad Aug 05 '17 at 13:49
  • TypeError: document.getElementById(...).getElementById is not a function at – jdio Aug 05 '17 at 13:54
  • You should check value of `document.getElementById('frame')` in console that has value or not. – Mohammad Aug 05 '17 at 13:57
  • 1
    Take a look at [this related question](https://stackoverflow.com/questions/139118/javascript-iframe-innerhtml) – Isac Aug 05 '17 at 13:59

2 Answers2

2

Use setTimeout() to delay your script. The iframe needs time to be loaded.

<iframe id="frame" src="frame.html"></iframe>
<script type="text/javascript">
setTimeout(function(){
  document.getElementById('frame').contentWindow.document.getElementById('test').innerHTML = 'abcdefgh';
},800);
</script> 

And notice the capital letters on innerHTML().

Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64
0

Hi here you have a solution



    setTimeout(function(){
        var iframe = document.getElementById('frame');
        console.log(iframe);
    });

Hope it helps