Extract part of HTML document in jQuery

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

Leave a Comment