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:

<html>
<script>
document.getElementById("test")..contentWindow.document.location.href = "www.google.com";
</script>
<body>

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

</body>
</html>


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

Thanks!

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:

$(document).ready(function(){
  
  
  $("#test").attr("src","http://stackoverflow.com/questions/42504395/change-to-change-iframe-source-dynamically");
  
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<iframe id="test" src="https://www.w3schools.com">
</iframe>

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