How to add an iframe via JS?

Asked

Viewed 38 times

1

I’m trying to add a simple iframe to an html page, but it’s not working:

var ifrm = document.createElement("iframe");
ifrm.setAttribute("src", "http://www.google.com/");
document.getElementsByClassName('col-12 col-md-4').appendChild(ifrm);

HTML:

<body>
    <div>
        <div class="col-12 col-md-4">

        </div>
    </div>
</body>

2 answers

1


The code snippet document.getElementsByClassName brings a array of information to work with your code need to indicate position, in this example I know you have a position so [0] and after appendChild:

var ifrm = document.createElement("iframe");
ifrm.setAttribute("src", "http://www.google.com/");
document.getElementsByClassName('col-12')[0]
     .appendChild(ifrm);
<div class="col-12 col-md-4"></div>

Note on the console.log

console.log(document.getElementsByClassName('col-12'));
<div class="col-12 col-md-4"></div>
<div class="col-12 col-md-4"></div>
<div class="col-12 col-md-4"></div>

demonstrating the amount of elements that are selected.

  • Excellent. And how would I style this iframe direct from js?

  • @Diegocândido https://stackoverflow.com/questions/5927012/javascript-createelement-style-problem take a look!

0

<div id="conteudo"></div>

<script type="text/javascript">
    document.getElementById("conteudo").innerHTML = '<iframe src="https://assets.b9.com.br/wp-content/uploads/2019/12/https___hypebest.com_image_2019_12_coca-cola-insiders-club-subscription-service-info-1-1170x720.jpg"></iframe>';
</script>

Hello! That would be a way to do too.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.