tags:

views:

133

answers:

6

How to insert dynamically iframe in a div with jQuery?

$(document).ready(function() {
$("div").html("<iframe src='http://google.com'&gt;&lt;iframe&gt;");  
});

This doesn't work.

+5  A: 

What you have works: http://jsfiddle.net/cUSVj/

Though keep in mind you can't do much with it after it's created if it's in not in the same domain, this is due to restrictions in place per the same-origin policy.

Edit: I was closing the tag thinking it was a paste error, you are indeed missing a / in your </iframe> closing tag...this will/won't work depending on how generous the browser is. Make sure to close it correctly so your HTML is valid, otherwise you'll have cross-browser issues, if it works to begin with.

Nick Craver
@lam3r4370 - It depends how that environment handlers an unclosed tag, see my updated answer, I re-read your question, didn't see it the first time, just blindly fixed it in jsfiddle before.
Nick Craver
Yes ,I tested it "inside" phpDesigner and that is because it didn't work...P.S:Yes ,it is mine paste error.
lam3r4370
+1 for showing me a new awesome thing, jsfiddle.net. What rock have I been under?
Tommy
+1  A: 

The actual jquery code looks fine, you may not be referencing the div correctly i.e.

#div - would be an element with the id "div"
.div - would be an element with the class "div"
James
+1  A: 

It works, I just tested it, what you might need is give jquery the id/class of the div you want to insert the iframe

eg. (id)

$("#myDiv").html("<iframe src='http://google.com'&gt;&lt;/iframe&gt;");  

eg. (class)

$(".myDiv").html("<iframe src='http://google.com'&gt;&lt;/iframe&gt;");
Flakron Bytyqi
+1  A: 

Yes. It is working fine.

Check here : http://jsbin.com/arolo3/2/edit

You should close the iframe tag. It might be the issue.

Krunal
+1  A: 

you did not close the iframe tag

<iframe>
</iframe>
+1  A: 
<html>

<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;&lt;/script&gt;
</head>


<body>
<script type="text/javascript">
    $(document).ready(function() {
        $("#frameDiv").html("<iframe src='http://google.com'&gt;&lt;/iframe&gt;");  
    });


</script>
<p>An IFrame should appear here</p>
<div id="frameDiv" style="width: 400px; height: 400px;"></div>

</body>
Tommy