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.
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>
innerHTML is one of the worst things one can do, because it destroys all nodes in the element. Also writing HTML in JS is often not advised.appendChild etc, but first you need to remove all content from the element. Why to overcomplicate?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
getByClassName method in JavaScript.