How to set iframe src attribute?

Member

by lily , in category: Third Party Scripts , 24 days ago

How to set iframe src attribute?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lizzie , 23 days ago

@lily 

To set the src attribute of an iframe, you can use JavaScript to target the iframe element and assign a new value to its src attribute. Here's an example code snippet to demonstrate how you can achieve this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<!DOCTYPE html>
<html>
<head>
    <title>Set iframe src attribute</title>
</head>
<body>
    <iframe id="myIframe" width="560" height="315" src=""></iframe>

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

    <script>
        function changeIframeSrc() {
            var iframe = document.getElementById("myIframe");
            iframe.src = "https://www.example.com";
        }
    </script>
</body>
</html>


In this example, we have an iframe element with the id "myIframe" and an empty src attribute. When the button is clicked, the JavaScript function "changeIframeSrc()" is triggered, which accesses the iframe element using its id and sets its src attribute to a new URL "https://www.example.com". You can replace this URL with any other web address you want to load in the iframe.