CSharpBeginner CSharpBeginner -4 years ago 81
Javascript Question

Change to change iframe source dynamically

I'm tried to simply change the iframe src at "run time" but it isn't worked for me.

What I'm tried:

document.getElementById("test")..contentWindow.document.location.href = "www.google.com";

<iframe id="test" src="https://www.w3schools.com">


But it isn't change the source,
What is the reason for that?


Answer Source

The problem is as your script tag is getting executed before the DOM loading; your document.getElementById("test") code returns nothing. You may use <body onload="myfunction()"> and write your required code in it so that it will get executed after the DOM loaded or you may try below jQuery apporach:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<iframe id="test" src="https://www.w3schools.com">

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download