9

I am using jQuery and this plugin to pull content from an external site.

It works great using the following code:

$.ajax({
       url: 'http://www.somesite.com/',
       type: 'GET',
       success: function(res) {
          $("#here").html(res.responseText);
       }
     });

But what I would really like to do, is only pull a section (div) from the target site, and I understand this is only possible when using the load() method, not GET.

I then found this code , but when I tried to build it into the code, it didn't seem to work, as such:

$.ajax({
       url: 'http://www.somesite.com/',
       type: 'GET',
       success: function(res) {
          $(res).find('div.content').each(function(){
              $('#here').append($(this).html());
         });

       }
     });

Looking into the request on Firebug, the request does seem successful, but the code can't seem to find the following tag: <div class="content row"> on the target site.

Do I need to make sure the target element has an #ID, instead of a class?

Thanks!

Mike Causer
  • 8,196
  • 2
  • 43
  • 63
kneidels
  • 956
  • 6
  • 29
  • 55

2 Answers2

6

Try using jQuery.parseHTML();

Description: Parses a string into an array of DOM nodes.

$.ajax({
   url: 'http://www.somesite.com/',
   type: 'GET',
   success: function(res) {
      var data = $.parseHTML(res);  //<----try with $.parseHTML().
      $(data).find('div.content').each(function(){
          $('#here').append($(this).html());
     });

   }
 });

because ajax response is a string and that way you can't use .find() method to find a dom node. so first you have to parse the string as dom nodes which you recieved from server then you can use .find() to select your target element.

Jai
  • 74,255
  • 12
  • 74
  • 103
3

In your original success callback you're fetching your html contents from responseText, you should do the same in the second case:

   success: function(res) {
      $(res.responseText).find('div.content').each(function(){
          $('#here').append($(this).html());
     });

Using class="content" or id should work. However, you should be aware that the code above adds all div's that have class content to your id="here" div, which might not be what you want. If you want just the contents of a specific element, use its id instead.

Rui
  • 4,847
  • 3
  • 29
  • 35