Grow your CSS skills. Land your dream job.

Ajax Load Container Contents

Published by Chris Coyier

With jQuery, you can load not just the contents of a URL, but a specific CSS selector from within that URL. It's like this.

$("#area").load("something.html #content");

That finds the content in the file something.html within the element with an ID of contentand puts it on to the current page, inside the element with an ID of area.

But let's say that something.html is actually extremely similar to the current page. Your goal is actually to replace #area with #area from something.html. So you do this:

$("#area").load("something.html #area");

But that's problematic, because now you'll end up with:

<div id="area">
    <div id="area">
         <!-- stuff -->
    </div>
</div>

And whatever triggered that action, if you did it again, would lead to even more nesting (bad).

The simple solution is to just grab all the contents of #area, rather than #area itself.

$("#area").load("something.html #area > *");

And the World's simplest (not feature full) demo:

View Demo

This is particularly useful when:

  • You are Ajaxing a site as a progressive enhancement, so each URL isn't just a fragment of data but a whole page that otherwise stands on it's own (and pages are of similar structure to each other).
  • You don't want to add markup to the page like <div id="inside"></div> just to get around this issue.

Thanks to Anthony Harris.

Comments

  1. Sam Najian
    Permalink to comment#

    Nice and simple post , I remember one of your screen-casts on ajax load , that’s really great!
    I really love your screen-casts ….. too little of them these days Chris! i miss them all!

  2. Jason Persampieri
    Permalink to comment#

    Oftentimes when you are doing something like this, the root element (#area, in your example) has potentially different attributes, making the “#area > *” not quite right.

    It’s for this reason that I have a “loadReplace” method that does the work for me :)

  3. Permalink to comment#

    “With jQuery, you can load not just the contents of a URL, but a specific CSS selector from within that URL. It’s like this.”

    You mean DOM selector, right?

    Anyways, good tip, I had this problem myself before and this is an elegant solution.

    • I mean CSS selector. jQuery uses Sizzle which is a selector engine that uses CSS selectors, so that’s what you use after the URL in the load function.

  4. Permalink to comment#

    thanks for tour article

  5. Christopher Smoak
    Permalink to comment#

    Just as a note. This does not allow you to load content from an external page. Found that out the hard way.

    • Permalink to comment#

      AJAX enforces a same domain policy and will only load content from the same address as the the page it’s on. To get around this you can use a server-side language like PHP to load the page and then echo/print it back out (basically a proxy)

  6. Permalink to comment#

    That’s really sweet. Watching my pages reload the same backgrounds over and over is annoying. Thanks!

  7. Permalink to comment#

    Loading a whole page, but getting only a part of it. Although this is possible with jQuery, I won’t use it ever. I would load only the data I want to. Any extra data loading sounds like a bad architecture to me..

    • Daniele
      Permalink to comment#

      Agree

    • Permalink to comment#

      aggree with you!

    • I understand what you mean, but it’s a little hard to argue things like this without any context. Such is the nature of isolated tips like this. This might be 100% perfect for some specific project.

    • Daniele
      Permalink to comment#

      @Chris: as you said, this tip is usefull when you have to edit/change/add functionality to an existing behavior, but i wont never *plan* this feature while making a project

    • Permalink to comment#

      That’s what I’m saying.

      If you need to load contents from a page which you show in browser as a “regular” web page, you’d better insert some server side logic in it which will filter the content when there’s XHR (it’s actually one if block in most cases).

      But loading a whole page via XHR when you need only one or two blocks from it, well, this is counter logical. You load extra content instead of saving it and reduce response’s size, which in turn will speed up the loading.

  8. Permalink to comment#

    hristo is right! why load an entire page if you only need parts of a page? it’s great to know that’s possible, i didn’t know that until now!

    • Daniele
      Permalink to comment#

      Please note that this behavior do load the entire page, and then jquery parse it to return just the selector.. so, i think this is a trick is a “quick’n’dirt” solution, definitely waste bandwith and browser resources ;)

  9. The only issue I can see with this is SEO. Search engines will not load this content to my best knowledge.

    When you have server side includes the search engine gets back the HTML in it’s entirety.

    With the above jQuery method, the browser is responsible for getting that HTML.

    I could be wrong but I think this would be bad for SEO.

    • Gabe
      Permalink to comment#

      I don’t think so. Unless I’m looking at it wrong, you could have a normal website set up with all of the pages linked with normal navigation that search engines would have no trouble spidering.

      This script just adds some progressive enhancement on top of that, so you don’t have to load the entire pages, but just the content. But without the script, it degrades to a standard website.

    • Permalink to comment#

      absolutely. good for users, too, not just SEO.

  10. Permalink to comment#

    Looks good, but you could probably just change the # and add a hidden class, that way it will only have to load each page once and still switch between them.

    function changePage(page) {
    if( $(page).css(‘display’) === ‘none’ ) { //If loaded and hidden
    $(page).fadeIn(‘fast’);
    }
    elseif( $(page).css(‘display’) !== ‘block’ ) { //If not loaded
    $(page).load(page+”.html #”+page+” > *”);
    }
    // Do nothing if already loaded and active
    }

    There’s an example of the functionality, although not very good quality code.

    • Permalink to comment#

      Whoops, this after [$(page).fadeIn(‘fast’);]

      $(‘.active’).removeClass(‘active’).fadeOut(‘fast’);
      $(page).addClass(‘active’);

  11. jas
    Permalink to comment#

    This still stumps me. Not necessarily the article which I think is superb, but the need for a hash.

    I think I have mentioned this before but why not do something like this?

    var $j = jQuery.noConflict();
    $j(document).ready(function() {
     $j('a').click(function() {
      $j.ajax({
        url:this.href, 
        success: function(value) {
         $j('#div-id').html(value);
        }
      });
     });
    });
    • Permalink to comment#

      Ah ha, so nothing to do with functionality but everything to do with crawlers and search engines.

      Hmmm, crawlers generally use the href attribute of links to index sites. So technically using a hash for each might cause more problems right?

      Having the page that just loaded show up in the URL bar doesn’t necessarily mean it works better for SEO, as most crawlers I have encountered search out the href attribute and follow that from the HTML.

      The only real reason I can see in using a hash for the URL would be for the end user.

  12. Davy Arnold
    Permalink to comment#

    I copied and pasted all the code into my CSS stylesheet and it doesn’t work. This site is about CSS Tricks right? ;P

    I kid, it looks like a pretty simple approach, like it.

  13. Gabe
    Permalink to comment#

    Once again, very timely. I’m building a website and have been using the Dynamic Page/Replacing Content (http://css-tricks.com/dynamic-page-replacing-content/) item to have a site that loads the background, navigation, etc only once and then loads the content of the rest of the site independently.

    But I’ve run into trouble when the content I’m loading has other jQuery goodies like tabs or a content slider in it. Somehow it all turns into a train wreck and stopped working. Maybe this technique will solve that…

    /fingers crossed

  14. I’m working on an app that will switch content on the frontpage (a custom PC app), a feature like this could be just what I need. ;)

    I’ll keep this tab open just in case.

  15. Very helpful. Remember to use a cool loading circle before content loads.

    I’m also very glad to see that you enjoy bacon!

  16. Steve
    Permalink to comment#

    Cool article

  17. Kanat B.
    Permalink to comment#

    Wouldn’t it be better to use $.get in this kind of situations?

    • If you needed to pass parameters or something, sure, but I don’t think it’s automatically better. They all use $.ajax internally anyway I’m pretty sure.

  18. Permalink to comment#

    Really cool but I’m wondering, how does this work in terms of SEO? When the page is crawled for the links inside, does it recognize them as links?

  19. Steve
    Permalink to comment#

    Cool

  20. Zoran
    Permalink to comment#

    I get this as quick solution while working with jQuery and i think it’s quite useful trick, cause when you get into situation where nothing else works, this can be real savior. It’s something you achieve with experience.

  21. “With jQuery, you can load not just the contents of a URL, but a specific CSS selector from within that URL”…

    Although, lets not forget that AJAX rocks because it can make your pages work better and faster for the end user. If you just load an entire page using AJAX, only to take one division from that massive page, you are wasting everybody’s bandwidth and time!

    Not to say this isn’t a great article though as it is a really handy trick – but please don’t do anything crazy with this knowledge.

  22. SpeedGun
    Permalink to comment#

    Another solution would be to have two div’s.

    Then when loading via JQuery

    $("#1").load("something.html #2");

  23. Permalink to comment#

    Hmmm …
    So try this in IE $(“#target”).load(url+” aside#All-Content > *”);
    Best regards! P.S. Load() function doesn’t works fine with HTML 5 tags in IE!

  24. Permalink to comment#

    can we load and add animation afterward?

    like

    $(“#area”).load(“something.html #area > *”).show(“slow”);

    • Pass function as second optional parameter:

      $(“#area”).load(“something.html #area > *”, function() {
      
          // do stuff after successful load
      
      });
    • Chris
      Permalink to comment#

      Chris, thanks for this. I’m working on a project with some pretty vanilla Ajax (pretty newb at Ajax) and this is just what I was looking for to make it better. I’m encountering issues when I want to run JavaScript from the ajaxed page – could your idea here be part of a solution?

  25. Permalink to comment#

    everyone keeps saying to avoid loading the whole page if you only need a small part. The question I have is:

    What is the best way to do this? Post a variable to test for in php? Seperate the area you need into a new file that is included in the original file (server side) and send the ajax request there? Or none of the above…

    I have a page/application that relies much more heavily on this jquery function than I would like. If I can get this fixed up to use less bandwidth it would be great, I just dont know the best way to get it done. Thanks for any advice in advance.

  26. Permalink to comment#

    I’ve done this for some time ago just for fun.
    Still works when javascript’s not activated.
    The only issue is the contact form whan loaded via ajax.

  27. Permalink to comment#

    Pretty cool, though I just found out the hard way that it doesn’t actually “grab all the contents of #area”, but instead selects every *DOM node* that is matched by the “> *” expression. So, for instance, if your markup goes like “Lorem Ipsum Content”, only “content” will be selected.
    Pretty logical when you think about it, but it took me a while to figure this out.

  28. Permalink to comment#

    Sorry, meant <section id=”area”>Lorem Ipsum<p>Content<p></section>.

  29. sdk
    Permalink to comment#

    is there a way to apply this to a page that doens’t end in .html?

    for instance, i would like to display the most recent div after a page reload, but i’m using wordpress and the url looks like so:

    http://civitasinc.com/2013/philosophy/#ideas

    so, I would like to display a div with the target of #ideas if the page reloaded or someone just happen to copy paste the url into another browser…

    thanks!

  30. Rohan

    Good one.

  31. MMN

    From where you can get a ” something.html ” file.

This comment thread is closed. If you have important information to share, you can always contact me.

*May or may not contain any actual "CSS" or "Tricks".