Extract part of HTML document in jQuery

ajax, jquery

Solution

You can use your standard selector syntax, and pass in the `data` as the context for the selector. The second parameter, `data` in this case, is our context.

$.post("getstuff.php", function(data){
  var mainDiv = $("#mainDiv", data); // finds <div id='mainDiv'>...</div>
}, "html");

This is equivalent to doing:

$(data).find("#mainDiv");

Depending on how you're planning on using this, `$.load()` may be a better route to take, as it allows both a URL and a selector to filter the resulting data, which is passed directly into the element the method was called on:

$("#mylocaldiv").load("getstuff.php #mainDiv");

This would load the contents of `<div id='mainDiv'>...</div>` in `getstuff.php` into our local page element `<div id='mylocaldiv'>...</div>`.

Problem

I want to make an AJAX call to an HTML-returning page, extract part of the HTML (using jQuery selectors), and then use that part in my jQuery-based JavaScript. The AJAX retrieval is pretty simple. This gives me the entire HTML document in the "data" parameter of the callback function. What I don't understand is how to handle that data in a useful way. I'd like to wrap it in a new jQuery object and then use a selector (via find() I believe) to get just the part I want. Once I have that I'll be passing it off to another JavaScript object for insertion into my document. (This delegation is why I'm not using jQuery.load() in the first place). The get() examples I see all seem to be variations on this: ``` $('.result').html(data); ``` ...which, if I understand it correctly, inserts the entire returned document into the selected element. Not only is that suspicious (doesn't this insert the `<head>` etc?) but it's too coarse for what I want. Suggestions on alternate ways to do this are most welcome.

Original source