6

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');

Fresheyeball
  • 29,567
  • 20
  • 102
  • 164

4 Answers4

7

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.

Community
  • 1
  • 1
d_inevitable
  • 4,381
  • 2
  • 29
  • 48
  • I would need to look at the inner detail of how jquery works to answer that. Basically jquery has a way on how it builds dom objects when when an html string argument is given. This was is simple not compatible with html strings that contain `body` and `html` tags, but fortunately it is not the only way and the way above is a different way of doing it. – d_inevitable Apr 05 '12 at 17:08
  • ok now I have a problem. IE says `SCRIPT600: Invalid target element for this operation.` on `doc.innerHTML` – Fresheyeball Apr 05 '12 at 22:23
  • As with everything else, IE needs workarounds: http://stackoverflow.com/questions/7474710/can-i-load-an-entire-html-document-into-a-document-fragment-in-internet-explorer – d_inevitable Apr 05 '12 at 22:27
1

When jQuery parses HTML it will normally strip out the html and body tags, so if the element you are searching for is at the top level of your document structure once the html and body tags have been removed then the find function may not be able to locate the element you're searching for.

See this question for further info - Using jQuery to search a string of HTML

Community
  • 1
  • 1
ipr101
  • 24,096
  • 8
  • 59
  • 61
0

Try this:

$("#element", $(response)).text()

This searches for the element ID in the $(response) treating $(response) as a DOM object.

mspisars
  • 844
  • 8
  • 21
-1

Maybe I'm misunderstanding something, but

.find('#element')

matches elements with an ID of "element," like

<p id="element">

Since I don't see the "tons of stuff" HTML I don't understand what elements you're trying to find.

David Gorsline
  • 4,933
  • 12
  • 31
  • 36