Open In App

Dynamically Create and Remove Iframe in JavaScript

Last Updated : 25 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
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">
    <title>Dynamically Create and Remove Iframes</title>
    <link href=
"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" 
          rel="stylesheet" 
          integrity=
"sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" 
          crossorigin="anonymous">
    <style>
        body {
            background-color: #f8f9fa;
            font-family: Arial, sans-serif;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100vh;
            margin: 0;
        }

        h2 {
            color: #28a745;
            margin-bottom: 20px;
        }

        h3 {
            margin-bottom: 20px;
        }

        .iframe-container {
            margin-bottom: 20px;
            border: 2px solid #dee2e6;
            padding: 10px;
            border-radius: 8px;
            background-color: #ffffff;
        }

        button {
            margin: 5px;
        }

        .no-iframes {
            display: none;
        }
    </style>
</head>

<body>
    <h2>GeeksforGeeks</h2>
    <h3>Dynamically Create and Remove Iframes</h3>
    <div id="display" 
         class="iframe-container"></div>
    <button class="btn btn-primary" 
            onclick="CreateIframeElement()">
      Create Iframe
  	</button>
    <button class="btn btn-danger" 
            onclick="RemoveIframeElement()">
      Remove Iframe
  	</button>

    <script>
        const CreateIframeElement = () => {
            // Check if there's an existing iframe to avoid multiple iframes
            const displayDiv = document.getElementById("display");
            if (displayDiv.childElementCount > 0) {
                alert("An iframe already exists. Please remove the existing one before adding a new one.");
                return;
            }

            // 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";
            el.style.border = "none"; // Optional: remove border if desired

            // Adding the created iframe to div as a child element
            displayDiv.appendChild(el);
        };

        const RemoveIframeElement = () => {
            const displayDiv = document.getElementById("display");
            // Check if there is at least one child to remove
            if (displayDiv.childElementCount === 0) {
                alert("No iframe to remove.");
                return;
            }
            
            // Remove the last child (iframe element) of div
            displayDiv.removeChild(displayDiv.lastChild);
        };
    </script>
</body>

</html>

Output:



Next Article

Similar Reads