Yash Meena
Yash Meena

Reputation: 31

how to create iframe inside multiple tags using JavaScript?

Here I want to insert iframe inside ins tag using JavaScript... here is the code that I am trying but its creating two iframes in side single ins tag.... here is the ins

<ins class="e120x600" id="120x600"></ins>
<ins class="e120x600" id="120x600"></ins>

Here is the JavaScript

<script>
  elem = document.querySelectorAll('.e120x600');
  for (let i = 0; i < elem.length; i++) {
    var size = elem[i].id
    var str = size.substring(size.indexOf("x") + 1);
    var H = str.replace('x', '');
    var str = size.substring(0, size.indexOf('x'));
    var W = str.replace('x', '');

    var e = document.createElement('iframe');
    elem[i].appendChild(e);
    g = e.style;
    e.scrolling = "no";
    e.frameBorder = 0;
    e.id = "ifrm";
    e.allow = "autoplay";
    e.id = "ifrm";
    e.width = W;
    e.height = H;
    g.border = 0;
    g.overflow = "hidden";

  }
</script>

Upvotes: 0

Views: 74

Answers (1)

Asaf
Asaf

Reputation: 1564

You got 2 elements with same id id="120x600", following that I've changed this

var size = elem[i].id

To this:

var size = elem[i].className.replace("e", "");

And now it seems to be working fine.

In the same matter- from fedeghe comment, I've changed this:

e.id = "ifrm";

To be unique like so:

e.id = "ifrm" + i;

elem = document.querySelectorAll('.e120x600');
for (let i = 0; i < elem.length; i++) {
    var size = elem[i].className.replace("e", "");
    var str = size.substring(size.indexOf("x") + 1);
    var H=  str .replace('x','');
    var str = size.substring(0, size.indexOf('x'));
    var W=  str .replace('x','');

    var e = document.createElement('iframe');
    elem[i].appendChild(e);
                    g = e.style;
                    e.scrolling = "no";
                    e.frameBorder = 0;
                    e.id = "ifrm";
                    e.allow = "autoplay";
                    e.id = "ifrm" + i;
                    e.width = W;
                    e.height = H;
                    g.border = 0;
                    g.overflow = "hidden";

}
iframe{
  background: green;
}
<ins class="e120x600" id="120x601"></ins>
<ins class="e120x600" id="120x602"></ins>

Upvotes: 1

Related Questions