1
<script type='text/javascript'>

    function cool()
    {
        var innerHtml = "<script></script>";//simply for demostration
        $("body").append(innerHtml);
    }
 </script>

The above will confuse browsers and will not render correctly before the cool function is even invoked. Why?

Bobo
  • 8,777
  • 18
  • 66
  • 85

1 Answers1

8

</script> will end a script element, so your script terminates in the middle of a string literal.

Browsers are not "confused", the HTML is simply wrong (and invalid … except in XHTML … but that only counts if you are using application/xhtml+xml … and then you get a different set of issues), which leads to the JavaScript being wrong.

Represent the sequence </ as <\/ in JS strings when you are using inline JS (as per the example in section 18.2.4 of the HTML 4.01 Recommendation).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335