Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery() on a well-formed HTML string results in Syntax Error, unrecognized expression

I've got a complete HTML document I'm pulling in with $.ajax(), and my .done() callback looks like this:

function (data, text_status, jq_xhr) {
  var $what_i_want = $(data).find('#what-i-want');
}

where data is a string that contains the entirety of a well-formed HTML document. This code never reaches .find().

Upon $(data), I get:

`Uncaught Error: Syntax error, unrecognized expression: <!DOCTYPE html>`...

The facts:

  • I'm using jQuery 1.9.0
  • The document is well-formed HTML5 according to the W3C validator.

I've used jQuery() to objectify many an HTML string, so I'm surprised this isn't working. Admittedly, I don't recall ever trying a whole document. Given the error, I'm guessing, perhaps, I need to escape this string somehow. But I'm not sure how.

Incidentally, this works:

var $what_i_want = $('#what-i-want', $.parseHTML(data))

But I can't figure out why the first approach fails.

like image 661
Dmitry Minkovsky Avatar asked Feb 27 '13 03:02

Dmitry Minkovsky


2 Answers

I had this same issue in a case where it was working on all sorts of other pages. They key for me was reading Brian's link on the upgrade-guide. The issue was this one page had a single blank line before the so even though I was only attempting to insert a portion of the returned html, it was not considering the returned data to be html. From the upgrade guide

As of 1.9, a string is only considered to be HTML if it starts with a less-than ("<") character.

Since it started with a blank line and not < it was not considered to be html. Thought I would add this contribution since I spent forever trying to figure out what the issue was.

like image 109
Phil Avatar answered Oct 06 '22 00:10

Phil


DOCTYPE isn't an normal html tag; I think it would need to be removed.

It might have trouble with body as well, since you can't embed a whole document within another. IIRC the internal method in jquery is just creating a span on the fly and updating the innerHTML.

like image 40
Kevin Seifert Avatar answered Oct 05 '22 23:10

Kevin Seifert