Ajax Load Container Contents

Avatar of Chris Coyier
Chris Coyier on

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 -->

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.