2

I forgot to include 'run multiple times in one page' on my last question located here: Create iframe with javascript appending to a div

I need to run the code on multiple div's within the same page. Right now the code below only runs once on the last div. For example if I have 3 div's, all 3 should have an iframe appended to it. Regular javascript. Trying not to use JQuery.

window.onload = function(){
var link = "http://www.somesite.com"
var iframe = document.createElement('iframe');
iframe.frameBorder=0;
iframe.width="300px";
iframe.height="250px";
iframe.id="randomid";
iframe.setAttribute("src", link);
document.getElementById("ad54").appendChild(iframe); //<--this id will be dynamically generated to match div's
}


<div class="ad" id="1"></div>
<div class="ad" id="2"></div>
<div class="ad" id="3"></div>

EDIT: Tested in IE9, Chrome, Safari, Firefox and opera. This code works. No JQuery or loops needed. This code will create the iframe wherever you use it.

var link = "http://www.somesite.com"
document.write(iframe);
var myIframe = parent.document.getElementById("randomid");
myIframe.height = 250;
myIframe.width = 300;
myIframe.src = link;
myIframe.style.border = "0px";
myIframe.style.padding = "0px";
Community
  • 1
  • 1
Patriotec
  • 1,104
  • 4
  • 22
  • 43
  • possible duplicate of [What's the best way to loop through a set of elements in JavaScript?](http://stackoverflow.com/questions/157260/whats-the-best-way-to-loop-through-a-set-of-elements-in-javascript) – Diodeus - James MacFarlane Apr 24 '12 at 18:22

2 Answers2

1
window.onload = function() {
  var elements = document.getElementsByTagName('div');
  for (var i = 0; i < elements.length; i++) {
    append_iframe( elements[i] );
  }
}

function append_iframe( div ) {
    var link = "http://www.somesite.com"
    var iframe = document.createElement('iframe');
    iframe.frameBorder=0;
    iframe.width="300px";
    iframe.height="250px";
    iframe.id="randomid";
    iframe.setAttribute("src", link);
    div.appendChild(iframe);
}
Dominic Goulet
  • 7,983
  • 7
  • 28
  • 56
0

Not a jQuery guy but I think this works

$("div").each(function(d) {
    var link = "http://www.somesite.com"
    var iframe = document.createElement('iframe');
    iframe.frameBorder=0;
    iframe.width="300px";
    iframe.height="250px";
    iframe.id="randomid";
    iframe.setAttribute("src", link);
    this.appendChild(iframe);
});
John Conde
  • 217,595
  • 99
  • 455
  • 496