Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery GET html as traversable jQuery object

Tags:

jquery

ajax

This is a super simple question that I just can't seem to find a good answer too.

$.get('/myurl.html', function(response){
     console.log(response); //works!
     console.log( $(response).find('#element').text() ); //null :(
}, 'html');

I am just trying to traverse my the html response. So far the only thing I can think of that would works is to regex to inside the body tags, and use that as a string to create my traversable jQuery object. But that just seems stupid. Anyone care to point out the right way to do this?

Maybe its my html?

<html> 
    <head> 
       <title>Center</title> 
    </head> 
    <body> 
        <!-- tons-o-stuff -->
    </body>
</html>

This also works fine but will not suit my needs:

$('#myelem').load('/myurl.html #element');

like image 540
Fresheyeball Avatar asked Apr 05 '12 16:04

Fresheyeball


Video Answer


1 Answers

It fails because it doesn't like <html> and <body>.

Using the method described here: A JavaScript parser for DOM

$.get('/myurl.html', function(response){
     var doc = document.createElement('html');
     doc.innerHTML = response;

     console.log( $("#element", doc).text() );
}, 'html');

I think the above should work.

like image 91
d_inevitable Avatar answered Sep 27 '22 23:09

d_inevitable