Eleni
Eleni

Reputation: 11

Why does modifying the html contents of a div (using JQuery) also change the rest of my page?

I am trying to load a page in a div in my page using JQuery. The variable "data" stores a string that is the html contents of the page I want to load.

I am using the command: $("#content").html(data); where "content" is the id of the div in which I want to load the page.

The problem is that, while this works as desired for some pages (only the contents of the div change and the rest of the page stays as before), in some other cases the page loads outside of the div element, starting at the top of my page and continuing over the other elements of my page, even though they are outside of the "content" div.

Upvotes: 1

Views: 71

Answers (1)

Adam
Adam

Reputation: 6733

I don't know for certain that it will solve the problem, but you really shouldn't be including entire pages (inlcuding html and head tags) in a div. Each page should have one html tag, one head tag and one body tag.

There are two options here:

  1. Load the sub-page in an iframe
  2. Load the contents of the body of the sub-page in the div

Option 1 is probably your best bet. With option 2 you can lose javascript and css from the head.

Do you have control over the page you want to put in the div? If it uses the same javascript files and style sheets as the "master" page then no problem.

Otherwise you could add them to the master page head (or body for scripts, but head for CSS), but then they can affect the rest of master page. If you can, then one solution to this is to have a container element with a distinctive class/id on the inserted page and make sure the CSS and javascript for that page only affects stuff inside that container.

For example (untested):

var sub_page = $(data);
$("#content").html( sub_page.find('body').html() );

var head = $('head');
sub_page.find('head script').each(function(){
   var src = $(this).attr('src');
   // Assume that inline script tags should be added but check those with a src to see they aren't already used on the master page.
   if( undefined === typeof src || '' === src || $('script[src="' + src + '"]').length == 0 ){
      head.append(this);
   }
});

CSS files would probably need to be treated in the same way as the scripts.

Upvotes: 1

Related Questions