简体   繁体   中英

How to add html attribute to (getElementById)

How can I add "src" in iframe attribute ( iframe src=" " ) to getElementById ( document.getElementById(" ").innerHTML = replaceurl )?

 <div class="output"> <iframe src="" style="width: 640px; height: 480px;"></iframe> </div> <script> function myFunction() { var geturl = document.getElementById("url").value; var replaceurl = ("https://docs.google.com/gview?url=" + geturl + "&embedded=true"); document.getElementById("").innerHTML = replaceurl; } </script>

You must use the setAttribute method for this ( https://developer.mozilla.org/de/docs/Web/API/Element/setAttribute ).

In your case, it can be done by writing the following:

// HTML
<iframe id="your-iframe" src="" style="width: 640px; height: 480px;"></iframe>

// JS
document.getElementById("your-iframe").setAttribute('src', replaceurl);

why not trying to add an id to the iframe element and pass urls to it by calling your function? like this:

<div class="output">
        <iframe src="" id="myIframe" style="width: 640px; height: 480px;"></iframe>
    </div>

    <script>
        function myFunction(id) {
          var geturl = document.getElementById("url").value;
          var replaceurl = ("https://docs.google.com/gview?url=" + geturl + "&embedded=true");
          document.getElementById(id).src = replaceurl;
        }
//call your function.
myFunction("myIframe");
    </script>

You can set the src of the <iframe> by directly assigning the new URL to the src property.

 function myFunction() { const geturl = document.getElementById("url").value, replaceurl = `https://docs.google.com/gview?url=${geturl}&embedded=true`; document.querySelector('.output iframe').src = replaceurl; } myFunction();
 <input type="text" id="url" value="https://stackoverflow.com/" /> <div class="output"> <iframe style="width: 640px; height: 480px;"></iframe> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM