Justin Force
Justin Force

Reputation: 6342

Replace content with jQuery.fn.load

I'm trying to write a client script to use .load in a non-typical way. I'm working with another site and I don't have access to change their generated code, so I have to do everything on the client side.

The page looks something like

<html>
  <!-- the head -->
  <body>
    <div id="body">
      <!-- the content -->
    </div>
  </body>
</html>

Now, I want to update the page with an XHR. I want to replace the contents of #body with the new contents of #body from the XHR. My first instinct was to do this:

$('#body').load('/ #body')

But that gives me a DOM that looks like this:

<html>
  <!-- the head -->
  <body>
    <div id="body">
      <div id="body">
        <!-- the content -->
      </div>
    </div>
  </body>
</html>

That's clearly not what I want. I want <!-- the content --> from the newly fetched copy to just overwrite <!-- the content --> from the current copy.

I have also tried things along the lines of

$.get('/', function(data) {
  $('#body').html($(data).find('#body').html());
}

to no avail. When I play with it, I find that $(data).find('#body') never finds anything.

Upvotes: 0

Views: 401

Answers (1)

bstakes
bstakes

Reputation: 1898

You can wrap the result of your XHR, assuming it is html in a jquery object, grab the body of the calling page and use replaceWith.

//snip
var xhrResult = $("<html><div id='body'>blah</div></html>"), // pretend this was returned
    newContent = xhrResult.filter("#body"),
    placeHere = $("#body");
placeHere.replaceWith(newContent);

Edited Based on this fiddle: http://jsfiddle.net/bstakes/VmhBW/

Upvotes: 1

Related Questions