Categories
JavaScript Answers

How to dynamically insert an iframe in a div with JavaScript?

Spread the love

Sometimes, we want to dynamically insert an iframe in a div with JavaScript.

In this article, we’ll look at how to dynamically insert an iframe in a div with JavaScript.

How to dynamically insert an iframe in a div with JavaScript?

To dynamically insert an iframe in a div with JavaScript, we can use createElement and appendChild.

For instance, we write:

<div>

</div>

to add a div.

then we write:

const div = document.querySelector('div')
const iframe = document.createElement('iframe')
iframe.src = 'https://example.com'
div.appendChild(iframe)

to select the div with querySelector.

Then we call createElement to create an iframe.

Next, we set the iframe’s src attribute by setting the src property.

Finally, we call div.appendChild with iframe to append the iframe as the child of the div.

Conclusion

To dynamically insert an iframe in a div with JavaScript, we can use createElement and appendChild.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *