Jquery Multiple load in a DIV

Here's the full source code for a solution.

I've hosted a working sample on JSBin.com: http://jsbin.com/ulodu (Editable via http://jsbin.com/ulodu/edit)

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<title>Sandbox</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<script>
$(function(){
  $.get(
    'http://jsbin.com/oyuho',
    function(response){
      /* 
        Wrap the response in a <div /> so that we can use
        find() instead of filter(). Also remove <script> tags.
        This is essentially what $.load() does.
      */  
      var responseWrapper = $('<div />').append(response.replace(/<script(.|\s)*?\/script>/g, ""))
      $('#content')
        .append(responseWrapper.find('#nicolas'))
        .append('<hr />')
        .append(responseWrapper.find('#antoine'));
    }
  );
});
</script>
</head>
<body>
  <div id="content"></div>
</body>
</html>

WHy not load them both in one call:

$('#right').load('textes.html #nicolas,#antoine');

EDIT
Inspired by Justice way I thought of the follwoing:

var $page = $('<div />').load('textes.html #nicolas,#antoine');
var $nicolas = $page.find('#nicolas');
var $antoine = $page.find('#antoine');
$('#right')
 .html($nicolas)
 .append('<hr/>')
 .append($antoine);

This will make only one (or two, depending on what firefox feels like) calls to the server. Thus saving bandwidth. But it also gives you more freedom in how to insert the elements and in which order.


Maybe I'm missing something but it seems like you all have been missing the fact that this is an ajax call and you are calling functions procedurally and not as a callback function based on a successful ajax response.

Besides, if you are doing anything more complex than loading some (X)HTML into an element, you should probably use one of the more powerful jQuery ajax methods (i.e., get() or post() or ajax()).

Assuming you'll get (X)HTML in the response:

// Only ONE ajax call and very simply parsing... 
$.get('textes.html', {}, function(data) {
    var $response = $('<div />').html(data);
    var $nicolas = $response.find('#nicolas')
    var $antoine = $response.find('#antoine');
    $('#right').append($nicolas).append($antoine);
},'html');

It's really as simple as that.

Tags:

Html

Jquery

Load