Extract part of HTML document in jQuery

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.


Solution 1:

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>.

Solution 2:

You could create a div and then put the HTML in that, like this…

var div = $("<div>").html(data);

...and then filter the data like this…

var content = $("#content", div.get(0));

…and then use that.

This may look dangerous as you're creating an element and putting arbitrary HTML into it, but it's not: anything dangerous (like a script tag) will only be executed when it's inserted into the document. Here, we insert the data into an element, but that element is never put into the document; only if we insert content into the document would anything be inserted, and even then, only anything in content would be inserted.