2

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/

3 Answers 3

4
success: function(result) {
    var div = $(result).filter('#items');
}
Sign up to request clarification or add additional context in comments.

4 Comments

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?
In terms of performance the best would be to have your php script return directly the partial HTML you need.
Good idea, would you regexp it? or is there some class to easily browse the DOM of a HTML file in PHP? phpQuery ? :P
No, no regexp, just separate the HTML fragment you need into another script.
2

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')

1 Comment

great i was thinking but you push it faster a bit great , you are up once!
1

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();

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.