admin管理员组

文章数量:1290189

I want to load an iframe using just javascript, so far I've been using this:

$(".punctis-social-box").html("<iframe></iframe>");

But since it is the only instruction I have that uses jQuery, I'll like not to depend any more on jQuery.

I want to load an iframe using just javascript, so far I've been using this:

$(".punctis-social-box").html("<iframe></iframe>");

But since it is the only instruction I have that uses jQuery, I'll like not to depend any more on jQuery.

Share Improve this question edited Mar 14, 2017 at 16:33 Gennadiy Litvinyuk 1,60713 silver badges24 bronze badges asked Jan 22, 2013 at 23:48 DomingoSLDomingoSL 15.5k25 gold badges104 silver badges179 bronze badges 1
  • 1 @Amadan I deleted my ment, I obviously misunderstood the question :) – Hanlet Escaño Commented Jan 22, 2013 at 23:56
Add a ment  | 

2 Answers 2

Reset to default 5

Maybe not the best way to start:

var elements = document.getElementsByClassName("punctis-social-box");
for (var i = 0; i < elements.length; i++) {
    elements[i].innerHTML = "<iframe></iframe>";
}

Or using querySelectorAll:

var elements = document.querySelectorAll(".punctis-social-box");
for (var i = 0; i < elements.length; i++) {
    elements[i].innerHTML = "<iframe></iframe>";
}

In order to avoid all bad practicesTM you may use document.createElement instead of explicit change of inner HTML:

var element = document.querySelector(".punctis-social-box"),
    iframe = document.createElement("iframe");

while (element.firstChild) {                  // the fastest way
    element.removeChild(element.firstChild);  // to clear the contents
}
element.appendChild(iframe);                  // adding new <iframe>

Method 1:

var social_boxes = document.getElementsByClassName('punctis-social-box');
social_boxes[0].innerHTML += '<iframe></iframe>'; // add to first element, loop thru "social_boxes" if you want to add iframe to all elements

Method 2 (better):

var social_boxes = document.getElementsByClassName('punctis-social-box');
var iframe = document.createElement('iframe');
social_boxes[0].appendChild(iframe); // add to first element, loop thru "social_boxes" if you want to add iframe to all elements

本文标签: javascriptLoading html on a div without jQueryStack Overflow