Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including the rendering of an HTML document into another HTML document

I have a string representing a stand-alone (and valid XHTML 1.0 Strict) HTML document, something like

var html = "<?xml ... <!DOCTYPE ... <html><head><style>...</style></head>
                  <body><table>...</table></body></html>";

The body of this HTML document contains a table whose CSS-style is described in the head of the HTML document.

I also have a DOM-tree of another HTML document. How can I include into this DOM-tree the DOM-tree of the table with the correct style (as described in the HTML-string)?

I am especially interested in a jQuery-based solution.

EDIT: To be more concrete, an example of an HTML-string that I'm talking about is embedded into this XML-document.

like image 840
Kaarel Avatar asked Apr 15 '09 17:04

Kaarel


1 Answers

I may be waaaay missing the point, but why not load the string into an IFRAME to render - this solves all the problems of having two separate DOM trees, and two separate sets of CSS rules, to me.

This code will do it:

$(function() {
        var $frame = $('<iframe style="width:200px; height:100px; border: 0px;">');
        $('body').html( $frame );
        setTimeout( function() {
                var doc = $frame[0].contentWindow.document;
                var $body = $('body',doc);
                $body.html(your_html);
        }, 1 );
});

(which I lifted from here: putting html inside an iframe (using javascript))

Then if you are concerned about the size of the IFRAME, you can set it with:

$frame[0].style.height = $frame[0].contentWindow.document.body.offsetHeight + 'px';
$frame[0].style.width = $frame[0].contentWindow.document.body.offsetWidth + 'px';
like image 122
DanSingerman Avatar answered Sep 29 '22 11:09

DanSingerman