How to dynamically add a single iframe to a parent element?

I’m having trouble with JavaScript when trying to add an iframe to a div. Here’s what I’m doing:

let frame = document.createElement('frame');
frame.src = 'https://example.org/';
frame.scrolling = 'no';
frame.style.cssText = 'border:0; overflow:hidden;';
document.querySelector('#container').appendChild(frame);

But when I use this on another website, I get two iframes instead of one:

<div id="container">
  <iframe src="https://example.org/" scrolling="no" style="width:300px; height:80px; border:0; overflow:hidden;"></iframe>
  <iframe src="https://example.org/" scrolling="no" style="width:300px; height:80px; border:0; overflow:hidden;"></iframe>
</div>
<script src="https://example.org/script.js"></script>

What’s causing this duplication? How can I fix it so only one iframe is created?

The issue you’re encountering is likely due to the script being executed multiple times. This can happen if the script is loaded more than once or if it’s triggered by multiple events. To prevent duplicate iframes, you can implement a check before adding the new frame. Here’s a modified version of your code that should work:

if (!document.querySelector('#container iframe')) {
    let frame = document.createElement('iframe');
    frame.src = 'https://example.org/';
    frame.scrolling = 'no';
    frame.style.cssText = 'border:0; overflow:hidden;';
    document.querySelector('#container').appendChild(frame);
}

This code first checks if an iframe already exists in the container. If not, it proceeds to create and append the new iframe. This approach ensures only one iframe is added, regardless of how many times the script runs.

hey there! looks like ur script might be running twice. check if it’s being called multiple times or if there’s another script adding iframes. try using an ID for the iframe and check if it exists before creating a new one. that should prevent duplication. good luck!

I’ve run into this issue before, and it can be frustrating. One thing I’ve found helpful is to use a unique identifier for your iframe. Instead of just checking if an iframe exists, you could give it a specific ID. Here’s what I mean:

if (!document.getElementById('myUniqueIframe')) {
    let frame = document.createElement('iframe');
    frame.id = 'myUniqueIframe';
    frame.src = 'https://example.org/';
    frame.scrolling = 'no';
    frame.style.cssText = 'border:0; overflow:hidden;';
    document.querySelector('#container').appendChild(frame);
}

This way, even if the script runs multiple times, it will only create the iframe once. It’s saved me a lot of headaches in similar situations. Also, make sure you’re not accidentally including your script file twice in your HTML. That’s another common cause of this kind of duplication.