How to change iframe src with JavaScript?

Estimated read time 1 min read

You can change the src attribute of an iframe in JavaScript using the following code:

document.getElementById("iframeId").src = "newUrl";

In this code, getElementById is used to select the iframe element, and then the src attribute is set to the new URL. Replace "iframeId" with the actual id of your iframe element, and "newUrl" with the desired URL.

For example:

<iframe id="myFrame" src="https://www.example.com"></iframe>

<button onclick="changeSrc()">Change src</button>

<script>
  function changeSrc() {
    document.getElementById("myFrame").src = "https://www.google.com";
  }
</script>

In this example, clicking the “Change src” button will change the src attribute of the iframe with id “myFrame” to “https://www.google.com“.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply