2

Let's say I have this page (page.html):

<html>
    <body>
    <h1>AAA</h1>
<script type="text/javascript">
    //<![CDATA[
$(document).ready(function() {

 $.get('page2.html', function(data){
  // I want to replace the entire HTML with the HTML of page2.html
  // but this doesnt' work
  $('html').replaceWith(data);
 });

});    //]]>
</script>
    </body>
</html>

Another page (page2.html):

<html>
    <body>
    <h1>BBB</h1>
    </body>
</html>

As you can see in my code snippet, I would like to fetch HTML from the page2.html and replace the entire content of page.html with the fetched response.

How to do that?

2 Answers 2

7

You can use document.open() to create a new page, document.write() to write the data and then document.close() to complete:

document.open("text/html");
document.write(data);
document.close();

https://developer.mozilla.org/en/DOM/document.open

Sign up to request clarification or add additional context in comments.

1 Comment

By the way this has some problems in IE (when page2.html has some javascript in it, it won't get executed).
0

Can't you just replace the html in the body tag with $('body').html(newContent)?

1 Comment

No. The returned HTML is complete also with html, head and other tags. It is returned as plain text so I cannot easily extract just body contents from it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.