jQuery: replacing HTML pages

Using jQuery's AJAX methods we can actually replace an HTML page with a completely new HTML page fetched from another location of our server. The entire page will be replaced, not only the content of the body element. That is, even the title of the page and its style sheets will be replaced. Let's see how.

We have two pages: the former is the caller that makes the AJAX request and the latter is the page to be fetched. The content type we're going to retrieve is text/html, so we need to set this in our AJAX call:

$(document).ready(function() {

  $('#replace').click(function(e) {
      type: 'GET',
      url: 'page2.php',
      dataType: 'html',
      data: null,
      success: function(page) {


The entire content of the html element of the caller page has been replaced by the external content of the requested page. However, there's a catch: browsers seem to ignore the body element of the fetched page, though they correctly display all its contents. You can see the demo below.


Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.