0

Update: It seems I didn't need in iframe for my purposes. Also seems jQuery/JavaScript: accessing contents of an iframe answers my question.

I've tried several variations on this and it's refusing to do anything. Sometimes I get an empty iframe, sometimes I get nothing at all.

I have an element with id 'contents' that is a direct child of the body. I wish to create a new iframe within the body, and move 'contents' and all its children into the iframe while preserving the dom hierarchy in context.

My current attempt is:

frame = $("<iframe frameborder=\"1\" height=\"100%\">");
        frame.appendTo("body");
        $("#contents").detach().prependTo($("body", frame));

But this just erases 'contents' into oblivion. Doing it without 'detach' has the 'contents' just stay put. Removing the 'body' selector from the prependTo erases 'contents' again, without it appearing in the iframe.

EDIT: Seems something is more fundamentally wrong, a simpler code such as the following fails as well:

frame = $("<iframe frameborder=\"1\" height=\"100%\">");
        frame.appendTo("body");
$("<b>text</b>").appendTo(frame);
Community
  • 1
  • 1
Rob F
  • 529
  • 6
  • 17

1 Answers1

0

You need to access the contents of the iframe instead of the iframe itself. So something like the following:

frame.contents().find('html body').html("<b>text</b>")

This injects the HTML into the body of the iframe.

http://api.jquery.com/contents/

nickles80
  • 1,101
  • 8
  • 10
  • I was doing that with the "body" selector in the 'frame' context. Anyway turns out that I need to do some nonesense with 'ready' and 'load' to stop the iframe overwriting its contents. And also that I don't even ned an iframe for my purposes. – Rob F Aug 07 '12 at 23:40