Loading content with jQuery AJAX - selecting the element to inject

Posted in Javascript -

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:

<div id="foo"></div>

We can load content into this with the following Javascript snippet (as long as we've also included the jQuery library) from the page /path/to/foo.html:

$('#foo').load('/path/to/foo.html');

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:

<html>
<head>
<title>My title goes here</title>
<link rel="stylesheet" type="text/css" href="/css/main.css"  />
<script language="javascript" src="/js/jquery-1.2.6.min.js" type="text/javascript">
</script>
</head>
<body>

<div id="blah1">
    ...
</div>

...

<ul id="navigation">
    <li><a href="">ABC</a></li>
    <li><a href="">DEF</a></li>
    <li><a href="">GHI</a></li>
</ul>

...

<div id="blah2">
    ...
</div>

</body>
</html>

and we only wanted to load the navigation list into our current webpage into #foo, we can do this:

$('#foo').load('/path/to/foo.html #navigation');

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.

As noted in the previous post, using .load() in this way will not produce any way of tracking errors if the content could not be loaded. Future posts will look at other ways to load content and look for errors. jQuery/Javascript posts are made on Tuesdays and Sundays so make sure to sign up to my RSS feed (see below) to make sure you don't miss out.



Related posts:


Comments