1

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.

1
  • 1
    @Amadan I deleted my comment, I obviously misunderstood the question :) Commented Jan 22, 2013 at 23:56

2 Answers 2

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>
Sign up to request clarification or add additional context in comments.

14 Comments

@PeeHaa How is this not the best way to start? His answer is completely valid.
Using 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.
I have just one element called punctis-social-box, so the For cycle is still useful?
@PeeHaa I simply "rephrase" the OP's code. Of course you can use appendChild etc, but first you need to remove all content from the element. Why to overcomplicate?
@PeeHaa That's only if you overright innerHTML, can you not just append to it (ie. innerHTML += "value") ?
|
4

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

4 Comments

There is no getByClassName method in JavaScript.
@VisioN Yes, there is, but it is not standard until HTML5 (although FF has had it since v3), if you want compatibility you would have to use nastier methods.
I really need a cross browser more compatible solution, so I need the "nastier methods" :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.