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

279
Visualizações
How to add JavaScript to newly created document with DOMImplementation.createHTMLDocument()

The following code snippet creates a new DOM document with a button inside it and adds it to an iframe. I want to add a JavaScript code inside the new DOM document so that when I click the button id dose something like alert.

I tried the following code but it doesn't work.

<html>

<head>
    
</head>

<body>

    <p><button id="btn" >Click Here</button>  to create a new document and insert it below.</p>
    <iframe id="theFrame" src="about:blank"></iframe>

    <script type="text/javascript">
    
        document.getElementById("btn").onclick = function () {
            var frame = document.getElementById("theFrame");
            var doc = document.implementation.createHTMLDocument("New Document");

            var button = doc.createElement("button");
            button.innerHTML = "Alert";
            button.setAttribute("id","btn1");

            var script = doc.createElement("script");
            script.innerHTML = "document.getElementById('btn1').onclick = function() {alert('button clicked!')};";
            
            try {
                doc.body.appendChild(button);
            } catch(e) {
                console.log(e);
            }

            try {
                doc.body.appendChild(script);
            } catch(e) {
                console.log(e);
            }

            // Copy the new HTML document into the frame

            var destDocument = frame.contentDocument;
            var srcNode = doc.documentElement;
            var newNode = destDocument.importNode(srcNode, true);

            destDocument.replaceChild(newNode, destDocument.documentElement);
        }

    </script>
    
</body>
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You really don't need to create a new document.

Just get a reference to the document within the frame and do everything within that context.

    document.getElementById("btn").onclick = function () {
        var frame = document.getElementById("theFrame");
        // reference to the iframe document instead of createHTMLDocument
        var doc = frame.contentDocument

        var button = doc.createElement("button");
        button.innerHTML = "Alert";
        button.setAttribute("id","btn1");

        var script = doc.createElement("script");
        script.innerHTML = "document.getElementById('btn1').onclick = function() {alert('button clicked!')};";
        
        try {
            doc.body.appendChild(button);
        } catch(e) {
            console.log(e);
        }

        try {
            doc.body.appendChild(script);
        } catch(e) {
            console.log(e);
        }

    }

Plunker demo

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