Inject document fragments using jQuery

The .load() function is one of the simplest forms of AJAX available in jQuery, but it’s really powerful. For those unfamiliar, it’s a bit different than most other AJAX functions in that it isn’t a global function, but a method on a jQuery object. when executed, it loads the requested URL and injects the resulting HTML into the elements contained in that object:


This is a really simple way of doing AJAX calls. One cool feature that is not often used, is the ability to inject only a fragment of that document, instead of the whole page, into our element:

$('#elementName').load('/dir/page.html div#divIDfrompage.html');

This would preform an XHR request for the requested URL, parse the returned document, find only the requested elements, and add them to the selected elements. Not bad for one line of code.

Read previous post:
PHP Script Load Time Snippet

Use this snippet to find out if your site is taking too long, and if it is, fix it. Insert...