Reputation: 1559
According to http://api.jquery.com/jQuery/#jQuery-html-ownerDocument you can create DOM elements on the fly from a string of raw HTML. This works, for example, on <p></p>
.
But when I try $('<script></script>')
, the </script>
part get's interpreted as the end of actual script and you will see the rest of the code as text in your browser like this: ').appendTo('body');
and I get the following error in Chrome console Uncaught SyntaxError: Unexpected token ILLEGAL
file.html
<!DOCTYPE HTML>
<head></head>
<body>
<script src="/jquery-2.1.1.min.js"></script>
<script>
$('<p></p>').appendTo('body');
$('<script></script>').appendTo('body');
</script>
</body>
I also tried $.parseHTML('<script></script>').appendTo('body');
but it gave me the same error.
I can't find any typo. Is this a bug in jQuery?
Upvotes: 0
Views: 1323
Reputation: 239382
This isn't a bug in jQuery, indeed it has nothing to do with JavaScript at all. This is about parsing HTML documents.
The HTML parser doesn't evaluate JavaScript. It cannot know the difference between the string "</script>"
and the actual closing </script>
tag. You cannot use the string </script>
inside your <script>
tags.
Consider:
<script>
alert("</script>"); // The script tag ends here...
</script> <!-- not here! -->
Instead, move the script to an externally-included file, or avoid the actual sequence of characters "</script>"
:
<script>
alert("</script" + ">");
</script>
Upvotes: 1