Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

114
Visualizações
How can I embed an iframe correctly with JavaScript?

How can I embed an iframe using JavaScript, that's being displayed where the code's being added? The code below displays the iframe ONLY above the footer, no matter where I add the code, whether it's in the header or the body.

var iframe_tag = document.createElement("iframe");
iframe_tag.setAttribute("src", "https://wikipedia.com");
iframe_tag.style.width = "100%";
iframe_tag.style.height = "480px";
document.body.appendChild(iframe_tag);

I know there are simpler ways to show an iframe, but I can only use JavaScript.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

When you use document.body.appendChild it is identical to just writing in the new html at the bottom, or literly appending the element to the bottom
This means that regardless of where the script is, it will always do this instead you should append to a predefined div (<div id="iframecontainer"> </div>)

let container = document.getElementById("iframecontainer");
container.appendChild(iframe_tag);

minimal example:

<!DOCTYPE html>
<html>
    <body>
        <script>
            let iframe = document.createElement("iframe");
            iframe.src = "https://wikipedia.com/";
            window.onload = () => {
                document.body.appendChild(iframe);
            }
        </script>
    </body>
</html

In my opinion you should, instead of creating an appending an element, just set the src of a pre-existing iframe (<iframe id="iframe"> </iframe>)

let iframe_tag = document.getElementById("iframe");
iframe.src = "https://wikipedia.com";

minimal example:

<!DOCTYPE html>
<html>
    <body>
        <iframe id="iframe"> </iframe>
        <script>
            let iframe;
            window.onload = () => {
                iframe = document.getElementById("iframe");
                iframe.src = "https://www.wikipedia.com/";
            }
        </script>
    </body>
</html

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda