Open In App

Dynamically Create and Remove Iframe in JavaScript

Last Updated : 04 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

JavaScript allows us to dynamically add and remove elements to the document. We can use event listeners and special JavaScript methods to create and remove HTML elements. This article focuses on creating and removing iframe elements dynamically using JavaScript.

Let’s first create a basic structure of the document using buttons and other elements. Buttons will allow us to call the JavaScript methods.

Flow Diagram Image for Dynamic Iframe:

Steps to Dynamically Create and Remove Iframe in JavaScript

  • First, Create an HTML Structure for the page containing title, 2 buttons (create and remove iframe) and dummy iframe using the html elements like div’s, span, iframe, buttons etc along with class name and some inline styles.
  • Define a function createIframeElement that creates and render the iframe dynamically on the web-page and assign with create iframe onclick event.
  • The createIframeElement uses createElement() to create iframe and its define properties like srcdoc, height and width using JavaScript.
  • Define a function removeIframeElement that calls when removeiframe button is clicked and removes the dynamically created iframe from the page with help of removeChild() method.

Example: This example demonstrates the code to dynamically create and remove iframe.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
</head>
 
<body>
    <h2 style="color:green;">
        GeeksforGeeks
    </h2>   
    <h3>Dynamically create and remove iframes</h3>
    <div id="display"></div>
    <button onclick="CreateIframeElement()">
        CreateIframe
    </button>
    <button onclick="RemoveIframeElement()">
        RemoveIframe
    </button>
    <script>
        const CreateIframeElement = () => {
            // Creating iframe element.
            let el = document.createElement("iframe");
 
            // setting the values for the attributes.
            el.srcdoc = `<h1>.Iframe Element.</h1>
            <p> Hello Geek! <br> How are you? </p>`;
            el.width = "400px";
            el.height = "200px";
 
            // Adding the created iframe to div as a child element
            document.getElementById("display").appendChild(el);
        }
 
        const RemoveIframeElement = () => {
 
            // Remove the last child ( iframe element ) of div.
            document.getElementById("display")
                .removeChild(document
                .getElementById("display").lastChild);
        }
    </script>
</body>
 
</html>


Output:

Dynamically create and remove iframe



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads