I created an iframe using jQuery that I want to insert into an existing div element. However, when I use innerHTML to insert it, it shows up as: "[object HTMLIFrameElement]"
What could be the reason for this?
Here is the example: /
I created an iframe using jQuery that I want to insert into an existing div element. However, when I use innerHTML to insert it, it shows up as: "[object HTMLIFrameElement]"
What could be the reason for this?
Here is the example: http://jsfiddle/MarkKramer/PYX5s/2/
Share Improve this question asked Oct 2, 2011 at 20:56 Mark KramerMark Kramer 3,2147 gold badges37 silver badges53 bronze badges 1- have a look here... stackoverflow./questions/3236430/… – kasper Taeymans Commented Oct 2, 2011 at 20:59
4 Answers
Reset to default 4You want to use the appendChild method rather than innerHTML. Change the last line in the JSFiddle from
iframediv.innerHTML = iframe;
to
iframediv.appendChild(iframe);
Edit to actually answer your question:
Your variable iframe
is a reference to a DOM element. It's object representation is an <iframe>
element while its textual representation is simply [object HTMLIFrameElement].
By using innerHTML
you are attempting to insert its textual representation into the DOM. This is just how the method works. You may e across JS code where elements are added to the DOM via innerHTML, but it's always with text, e.g.
element.innerHTML = '<div>some text</div>';
In this case the browser will correctly add a <div>
node as a child of element
.
For your <iframe>
element to be inserted into the DOM using the variable iframe
, you must use the appendChild method which will add the IFrame object as a child node to iframediv
.
$('#iframecontainer').append(iframe);
instead of
var iframediv = document.getElementById('iframecontainer');
iframediv.innerHTML = iframe;
should fix the problem
var new_iframe = $("<iframe></iframe>");
new_iframe.appendTo($("#div_to_insert_into"));
The idea behind (most) of the posted solutions is that you can work with your iframe and it's container as jQuery objects instead of regular dom elements. A jQuery object is a reference to a div
or an iframe
that has access to all of jQuery's awesome methods... like .append()
and .click()
.
Generally speaking, jQuery's real purpose is to turn lines of code like
var iframediv = document.getElementById('iframecontainer');
...into ...
var iframediv = $("#iframecontainer");
...which you can then use to do with whatever you please, like
iframediv.appendTo("#anotherDiv");
Good luck.