views:

306

answers:

2

I'm have some that uses jQuery.clone() to get the html of a page and then add it to a pre tag. It works correctly in Firefox and Chrome, but nothing happens in IE:

<!DOCTYPE html>
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"&gt;&lt;/script&gt;
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"&gt;&lt;/script&gt;
<![endif]-->
<script>
$(function(){

  $('button').click(function(){
    var $clone = $('html').clone();
    $('#output').text($clone.html());
  });

});
</script>
<style>
  article, aside, figure, footer, header, hgroup, 
  menu, nav, section { display: block; }
</style>
</head>
<body>
  <button>run test</button>
  <pre id="output"></pre>
</body>
</html>

Is there any know bug with IE that prevents this, or am I doing something wrong?

(I need to clone it because I'm doing some changes to it before outputting it)

+2  A: 

If you want to just show the page text in the page, try this:

$('button').click(function(){
  $('#output').empty().html(('<html>\n  ' + $('html').html() + '\n</html>')
     .replace(/&/gm, '&amp;')
     .replace(/</gm, '&lt;')
     .replace(/>/gm, '&gt;')
     .replace(/\r/gm, '')
     .replace(/\n/gm, '<br>')
   );
});

That works for me in Chrome, Firefox, and IE8.

Pointy
thanks :) but i also need to remove some elements from the original html, how can I do that with you method?
mofle
Well, you could do your `clone()` operation, mess with it however you want, and then work with the `.html()` value of the result.
Pointy
+1  A: 

This seems to work in IE, Firefox & Safari. I'm calling the javascript DOM API cloneNode() method instead of jQuery's clone(). Don't know why it works. You should probably do some more browser testing.

var $scripts = $('script');            // Cache all scripts in the document

var html = $('html').get(0).cloneNode(true);  // Clone HTML using DOM API

var $html = $(html);                     // Make jQuery object from cloned HTML

$('script', $html).each(function(i) {       // Loop through scripts in $html
    this.text = $scripts.get(i).innerHTML;  //  replacing content with that
});                                         //  from the cached $scripts

$('#output').empty().text($html.html());    // Append to #output
patrick dw
almost, but it removes embedded scripts. like if i have <script> var test = true; </script>. only the <script></script> tags are left. any ideas?
mofle
OK, I think I've got it. Since IE kindly leaves us the empty `script` tags, all we need to do is cache those first, clone our `html`, then updated the empty `script` tags with the content of the cached ones. Seems to work. I updated my answer. Let me know.
patrick dw