0

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!

1

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your help. I'm not sure what's going on here. But I was unable to get this to work. jsbin.com/avamo I 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.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.