On Wednesday I looked at how to load content with jQuery via AJAX using the .load() function. This is the second part of that post which looks at how to just select a portion of the content loaded and inject just that part into the current webpage.
Using a similar example to my previous post, the current webpage that we wish to inject content into has a placeholding <div> that looks like this:
If foo.html is a regular HTML page containing <html> <script> etc tags then it can completely screw with your existing page, so it either just needs to contain very basic content, or you can inject just a section of the page into your current webpage.
For example, if foo.html contains something along these lines:
and we only wanted to load the navigation list into our current webpage into #foo, we can do this:
Note that we have specified #navigation after the path to the filename to be loaded. This tells jQuery to only inject the element #navigation into our current webpage's #foo element. The resulting #foo <div> would now look like this:
<div id="foo"> <ul id="navigation"> <li><a href="">ABC</a></li> <li><a href="">DEF</a></li> <li><a href="">GHI</a></li> </ul> </div>
You can use any normal jQuery selectors to choose which elements to inject into the current webpage, so the following would be equally valid:
$('#foo').load('/path/to/foo.html #navigation li');
This would just load the <li> elements from #navigation, resulting in invalid HTML but the jQuery call would succeed.