Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to empty the contents of a div and insert a working iFrame?

I am trying to create a function that empties a video container of its contents (thumbnail / playbutton) and replace it with an iframe of for example vimeo or youtube.

So far I got this:

replaceIframe(){
    const parser = new DOMParser();
    const videoContainer = document.querySelector('#landingspage .video-container');
    const iframe = document.querySelector('#landingspage .iframe-container').innerHTML;
    const iframeHTML = parser.parseFromString(iframe, "text/html");

    console.log(iframeHTML);

    if(videoContainer !== null){
        videoContainer.addEventListener('click', (ev) => {
            ev.preventDefault();
            videoContainer.replaceChildren(iframeHTML);
        });
    }
}

But this gives me the error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Uncaught DOMException: Failed to execute 'replaceChildren' on 'Element': Nodes of type '#document' may not be inserted inside nodes of type 'DIV'.
    at HTMLDivElement.

How can I fix this? I first tried it without the parser object but then it just replaces the contents with a string of the iframe html.

>Solution :

Use videoContainer.innerHTML = iframeHTML instead of videoContainer.replaceChildren(iframeHTML);

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading