views:

282

answers:

2

I know you can get the innerHTML doing something like this, with jQuery,

$('iframe').load(function(){
  alert($(this).contents().find('body').html());
});

This gets the innerHTML of the body tag. But I want it all. I want the HTML tag and the doctype. The whole source code basically. And I want to be able to edit it as a whole as well. By "as a whole", I mean I wanna be able to do something like this,

$('iframe').html('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html>
<head>
  <title>title</title>
</head>
<body>
hello world
</body>
</html>');

How do I do this?

Note: I realize DOM is handled differently in different browsers and so the innerHTML from Opera will look different than the one from Firefox. But it's no biggie.

A: 

I assume this document you are accessing is on the same server? Obviously being able to access (and edit!) the contents of another website would be very dangerous.

$('iframe').contentWindow.document.documentElement.outerHTML will contain the full html tag and its contents. outerHTML isn't exactly cross-browser, and you may want to parse the attributes of the documentElement object instead. Note that you can't edit the outerHTML (at least in WebKit), so you can use innerHTML to edit the contents.

$('iframe').contentWindow.document.doctype represents the DOCTYPE. You can't get the actual tag, but you can retrieve the information from its attributes. Here is the MSDN reference for the !DOCTYPE element.

ACoolie
jQuery doesn't have a `contentWindow` property...
geowa4
also, `documentElement`? goin' old school?
geowa4
Yes it's in the same server.
this is a dead end
A: 

document.write is your friend.

For example:

var iframeEl = document.createElement('iframe');
document.body.appendChild(iframeEl);

var oFrame = window.frames[window.frames.length - 1];
oFrame.document.write('<html><head><title>foo</title></head><body>bar</body></html>');

oFrame.document.body.innerHTML; // "bar"
kangax
oFrame.document isn't x-browser; use `oFrame.contentDocument || oFrame.contentWindow.document`
geowa4
@geowa4 Not exactly. You confuse `contentDocument` property of `HTMLIframeElement` - http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-67133006 with `document` property of `Window` object (available through `window.frames` collection). Notice that I'm accessing document via iframe's corresponding window object, not via iframe element's `contentDocument` property.
kangax