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 A
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.
You may want to look at the dataFilter()
parameter of the $.ajax
method. It lets you do operations on the results before they are passed out.
jQuery.ajax
You can use load on a new element, and pass that to a function:
function handle(element){
$(element).appendTo('body');
}
$(function(){
var div = $('<div/>');
div.load('/help a', function(){handle(div);});
});
Example: http://jsbin.com/ubeyu/2
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>
.
You can do the thing this way
$.get(
url,
{
data : data
},
function (response) {
var page_content = $('.page-content',response).get(0);
console.log(page_content);
}
)
Here in the console.log you will see the inner HTML of the expected/desired portion from the response. Then you can use it as your wish