views:

89

answers:

2

I have some very simple sample code like this:

$.ajax({
  url: 'demo2.htm',
  success: function(loadeddata){
    $("#loaded_data").after(loadeddata);
    alert('success');
  },
  error: function(){
    alert('failure');
  }
});

Loaded data currently returns everything. What I need to is to get only a specific div and after it add it to #loaded_data.

How do I do that?

Thanks!

+4  A: 

This is how jQuery does it internally:

$("<div/>").append(loadeddata).find('#mydiv');

If you expect to have SCRIPT tags in the HTML, you should throw this in to avoid any 'Permission Denied' errors in IE:

$("<div/>").append(loadeddata.replace(/<script(.|\s)*?\/script>/g, "")).find('#mydiv');

EDIT:

You are missing the point of what is supposed to be happening.

By doing $("<div/>").append(...); jQuery creates a dummy <div> and gets the browser to parse the HTML by inserting it inside of the <div>. Once that's done, we can find the DIV we want, and return the HTML. So the more proper code sample I should have put above looks like this:

var html = $("<div/>").append(loadeddata).find('#mydiv').html();
$('#whereIwantIt').html(html);

As you can see in the link, this does what you want.

Paolo Bergantino
Thanks for your help. I'm not sure what's going on here. But I was unable to get this to work.http://jsbin.com/avamoI only want to add #hello to the page. I'm not sure why it turned white after ajax completed. But in the flash there I saw the entire page being added, not just the part I specified.Thanks.
Mark
A: 

OK, here's a new pastebin with find and the script problem fixed as Paolo mentioned.

http://jsbin.com/esoze/edit

As you can see the entire HTML of the page is embedded, rather than just the specified element.

Mark