views:

36

answers:

3

I use $.ajax() to get some HTML pages from my server. The retrun contains the full HTML result. But i am only interested in a very specific div inside this document.

The only given thing is that my ajax success function returns a JSON object. I have made a PHP proxy file i use for other stuff that returns me a JSON object with the headers, some information to the file I'm loading and its contents. So basically i have a string containing the whole HTML of the page.

Actually i make it like that: $($(data.content)[21]) but this is awful example of jquery (Because i use the $ selector twice, and the HTML could by changing and the div I'm interested in could be changing position in the jquery array). I would like to get only the div <div id="items">...</div> and its contents and only then select it with jquery.

What is the best practice for this case? What would your approach look like?

PS: in case that my example is not clear, your can see an example here: http://meodai.ch/content_slider/

+2  A: 

Try this:

var $items = $(data.content).find('#items')

or if #items is at the top level of the <body>, then do this instead:

var $items = $(data.content).filter('#items')
patrick dw
great i was thinking but you push it faster a bit great , you are up once!
JapanPro
+1  A: 
success: function(result) {
    var div = $(result).filter('#items');
}
Darin Dimitrov
I have done this first, but then figured it would be kind a waste of resources to select the whole result with jquery and only then look for #items. Is it slower to extract the div from the string first and then select it with jquery?
meo
In terms of performance the best would be to have your php script return directly the partial HTML you need.
Darin Dimitrov
Good idea, would you regexp it? or is there some class to easily browse the DOM of a HTML file in PHP? phpQuery ? :P
meo
No, no regexp, just separate the HTML fragment you need into another script.
Darin Dimitrov
+1  A: 

Once you parse the JSON response and get the HTML out of it, wrap it in a jQuery object:

var $j = $(htmlGoesHere);

Then, extract the HTML of the div:

var itemsHTML = $j.find("#items").html();
SimpleCoder