views:

55

answers:

2

Is there a way to use jQuery.html() and not loose the scripts and styles? or any other non-jQuery way?

I'm trying to output the full HTML of the page the user is on. Is this even possible?

+2  A: 

jQuery.html() removes scripts and styles

That isn't my experience (see below). In practice, you have to be aware that what you get back by querying the DOM for HTML strings is always going to be the interpreted HTML, not the original, and there will be quirks (for instance, on IE all the HTML tag names are IN UPPER CASE). This is because jQuery's html function relies on the browser's innerHTML property, which varies slightly browser to browser. But the demo below includes both style and script tags on Chrome 4, IE7, and Firefox 3.6; I haven't tried others, but I would expect them to be okay.

If you want to get the content of externally-linked pages as well as the inline content, you will naturally have to parse the result and follow the src (on scripts), href (on links that have rel = "stylesheet"), etc...

Demo:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Test Page</title>
<style type='text/css'>
body {
    font-family: sans-serif;
}
</style>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'&gt;&lt;/script&gt;
<script type='text/javascript'>
(function() {
    $(document).ready(pageInit);

    function pageInit() {
        $('#btnGo').click(go);
    }

    function go() {
        alert($('html').html());
    }
})();
</script>
</head>
<body>
<input type='button' id='btnGo' value='Go'>
</body>
</html>
T.J. Crowder
you are correct. didn't think to try $('html'). thank you :D
mofle
@mofle: Ah, cool. :-)
T.J. Crowder
A: 

I see 2 scenarios here

  1. you use jQuery.html(yourHTML) to overwrite the entire html of the page, so even the script tags were overwritten...
  2. you use jQuery.html() to retrieve the entire document html. if this is the case you need tu ensure that the element on which .html() function is used, is the entire html... as T.J. Crowder suggested $('html').html()
Alex Pacurar