Ken Browning Ken Browning - 1 year ago 136
jQuery Question

How do I replace the entire HTML node using jQuery

I have a string which looks like:

<html><head><title>example</title></head><body>some example text</body></html>


I get this string returned as a result to an AJAX request.

I would like the browser to render and display that string. The idea would be to do something like:

$('html').parent().html(myString);


Well, that doesn't work. I've attempted to use an IFRAME but I haven't figured out how to get that to work either.

Note: It is impossible for me to change this string. It is also impossible for me to regenerate this string in a subsequent call to the server (otherwise I could just redirect the browser to that url).

Answer Source

The document.open/write/close methods will do what you want:

var newDoc = document.open("text/html", "replace");
newDoc.write(myString);
newDoc.close();

Unless you pass in the replace parameter, the document.open call adds page history. So users would have to click back twice to go to the previous page.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download