Friday, February 11, 2011

jQuery: Partial Loads

I had an issue in jQuery the other day where a load() command wasn't working properly.  There could have been an error in my target HTML, but I sure couldn't find it. What I was doing was using Ajax to load table rows into a form.  The HTML being loaded just wasn't maintaining structure (<TD>s nested into a <TR>.  To fix this I read about jQuery partial load.  I don't know how I never saw this before as I can see a few cool uses.

A partial load works like this: add a selector after the url in a load() method call and jQuery will load all matching elements into your specified element.
// load all td elements from the specified url into myElement

$('#myElement').load('http://url/template.html td');

This is shorthand for the following:
$.get(''http://url/template.html', function (html) {

    $(html).find('td').each(function (){

        $('#myElement').append(this);

    });

}

The documentation can be seen here.

1 comment: