jQuery + client-side template = "Syntax error, unrecognized expression"

Evgeny picture Evgeny · Jan 15, 2013 · Viewed 121.2k times · Source

I just updated jQuery from 1.8.3 to 1.9, and it started crashing all of a sudden.

This is my template:

<script type="text/template" id="modal_template">
    <div>hello</div>
</script>

This is how I read it:

modal_template_html = $("#modal_template").html();

This is how I transform it into jQuery object (I need to use jQuery methods on it):

template = $(modal_template_html);

... and jQuery crashes!

Error: Syntax error, unrecognized expression: <div>hello</div>

slice.call( docElem.childNodes, 0 )[0].nodeType;

jquery-1.9.0.js (line 3811)

However, if I declare template as a plain text variable, it starts working again:

var modal_template_html = '<div>hello</div>';

Can anyone help me to figure this out?

UPDATE: Jquery team heard and changed things back to normal in 1.10:

The biggest change you’re likely to see is that we’ve loosened up the criteria for HTML processing in $(), allowing leading spaces and newlines as we did before version 1.9

Answer

Evgeny picture Evgeny · Jan 16, 2013

Turns out string starting with a newline (or anything other than "<") is not considered HTML string in jQuery 1.9

http://stage.jquery.com/upgrade-guide/1.9/#jquery-htmlstring-versus-jquery-selectorstring