Search code examples
jqueryjquery-load

Update multiple areas with jQuery.load()


jQuery allows you to update a single part of a page if it has an ID:

$('#myDiv').load('http://my/url/#myDiv');

I need to update several parts of a page (around a form). I realise I could:

  • Call load one time per region I want to update, but this is crazy-inefficient.
  • Restructure how I'm doing things, so detach the original form, .load(...) the whole page and reattach my old form... but this has a habit of messing around with focus states.

I guess what I'm after is a good way to download the page (as a jQuery object) and then cross-update particular sections. I'm assuming that's how the existing .load() code works. But how do I actually do that?


Solution

  • One solution would be to use $.get:

    $.get('http://my/url/', function(response) {
        var $page = $(response);
    
        $("#myDiv1").replaceWith($page.find("#myDiv1"));
        $("#myDiv2").replaceWith($page.find("#myDiv2"));
    });
    

    One important thing to note is that jQuery will remove elements like <html>, <body> or <header>, so if the element is a direct descendant of one of those, you could use .filter to find it instead.