jQuery: query a $.get() returned string

How can i query a string i get via $.get? for example, i want form google only the body html:

$.get("www.google.com", function(data){
var body = $("body", data).html(); //This doesnt work

Is it even possible? thanks



Nope, jQuery can't directly access the DOM of a page that was loaded via an XmlHttpRequest. In order to do this, you would have to use an HTML parser written in JavaScript, like the one that John Resig wrote. It's still a much harder task than you were probably expecting though.


One thing is that this wont work because you need a HTML parser. The other is that unless you are doing this on www.google.com this wont work because of the same origin policy. There are ways to circumvent this, most popular is JSONP, but this can be done manually as well, without using the jsonp method defined by jQuery.

If you don't want to go through the problems of getting content from a different domain in your JavaScript, an alternative method would be to use your server be it, PHP, .NET ect to fetch the remote page and then return it the the JavaScript using AJAX. This will ofcause be a little more time consuming than doing it directly in the js, as you are doing 2 requests instead of one. However, depending on your server tools, you might have an easier time parsing the html instead of doing that in the js, so you more easily can get the stuff you want to your page.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.