markcruz
markcruz

Reputation: 1687

jQuery ajax call Returning particular HTML elements

I tried this code:

$.post('/script', function(result) {
    var foo = $(result).find('#foo');
    $('#result').html(foo);
});

Here's the return html:

<div id='foo'>
  Content.
</div>
<div id='new'>
   New data
</div>

After alerting variable foo it returns an object. And the html becomes empty. I would like to print a specific html block (#foo only not #new).

From jQuery documentation:

$.post( url, { s: term } ,
      function( data ) {
          var content = $( data ).find( '#content' );
          $( "#result" ).html( content );
      }
);

This (var content) would also result to object and printing an empty string on #result.

Upvotes: 1

Views: 234

Answers (2)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195972

This happens because both #foo and #new are at the top level.

The .find() method looks for descendants. so you will need to wrap them in another div either at the server-side (result) or the jQuery level.

So either change html to

<div>
   <div id='foo'>
     Content.
   </div>
   <div id='new'>
      New data
   </div>
</div>

or at jquery level

$.post('/script', function(result) {
    var foo = $(result).wrapAll('<div>').parent().find('#foo');
    $('#result').html(foo);
});

If you use the HTML solutions you could however use the .load method which can load page fragments

$('#result').load('/script #foo');

This will load the element with id foo from the /script page and put it in #result element.

Upvotes: 1

2GDev
2GDev

Reputation: 2466

foo is an object... foo.html() is what you want, so you've to change : $('#result').html(foo); in $('#result').html(foo.html());

Upvotes: 0

Related Questions