'How to change the iFrame src on click of a button

 <section class="ep1">
        <iframe src="https://example.com" width="640" height="480" allow="autoplay"></iframe>
 </section>
<button onclick="setURL(`https://example.com/new`)"> Episode 2 </button>
 <script>
        function setURL(url) {
            document.getElementById('iframe').src = "url";
        }
 </script>

This code won't work on clicking the button.

I tried the given code, I am expecting that onclicking the button src of the iframe should change.



Solution 1:[1]

document.getElementById('iframe') will look for an element with ID="iframe". The given iframe does not have an ID.

try:

<iframe id="iframe" src="https://example.com" width="640" height="480" allow="autoplay"></iframe>

or:

document.getElementsByTagName('iframe')[0].src = ...

Solution 2:[2]

you are selecting an element with an id of iframe. your element does not have an id. This should work (this is selecting an element with the iframe tag):

     <script>
            function setURL(url) {
                document.querySelector('iframe').src = "https://website.com";
            }
     </script>

Solution 3:[3]

document.getElementById('iframe').src = "url";

You should remove the quotations around url and also give the iframe a id. So it should look like this

document.getElementById('iframe').src = url;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ricdijk
Solution 2 bguiz
Solution 3 Vian du Plessis