0

I evaluated data string inside .get function:

$.get(url, function(data) {
  var divHtml = $(data).find("#comments-comments").html(); 
})

data is a returned page like that:

"<  !DOC TYPE html >\r\n\r\n< html ... < / body >\r\n\r\n< / html >"

But divHtml doesn't give the div I am interested.

var divHtml = $(data).find("#comments-comments").html();    // data is the string above.

How can I evaluate #comments-comments div?

Thanks.

Note: I purposefully inserted spaces inside the string since stackoverflow didn't show original string.

horse
  • 707
  • 4
  • 11
  • 30

1 Answers1

0

I assume you're asking: why doesn't

$("<body><div id='comments-comments'><b>hello</b></div></body>").
  find("#comments-comments").html()

return

"<b>hello</b>"

?

jQuery strips out e.g. <html> and <body>, so the <div> is effectively the top-level element. find searches for subelements.

Instead you can use filter which filters top-level elements:

$("<body><div id='comments-comments'><b>hello</b></div></body>").
  filter("#comments-comments").html()

More detail here: Using jQuery to search a string of HTML

Community
  • 1
  • 1
Henrik N
  • 15,786
  • 5
  • 82
  • 131
  • This solved my problem. Thanks. I try to update my page without Ajax solutions which seems to me complex. What do you say about that? – horse Jun 29 '14 at 11:56
  • @user2356198 I'm not sure I understand what you're asking. But I realized what you're doing is probably reinventing something that is built into jQuery – look into how `.load` supports fragments: http://api.jquery.com/load/ – Henrik N Jun 29 '14 at 13:36