Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery; correctly selecting contents of a script tag

Tags:

jquery

I have a single page web application using jquery and a set of embedded templates. A template may contain tag like below:

<script type="html/template" id="sample">

<script type="text/javascript" charset="utf-8">alert('x');</script>


</script>

and a jquery code to retrive the template is

$("#sample").html();

The output of above jquery command is

<script type="text/javascript" charset="utf-8">alert('x');

Instead of

<script type="text/javascript" charset="utf-8">alert('x');</script>

How can I fix this output ?

like image 873
Ali Salehi Avatar asked Oct 08 '22 12:10

Ali Salehi


2 Answers

I am not sure this will help you.

 var a = $("#sample").html() +'</'+'script>';

 alert(a);​

fiddle link: http://jsfiddle.net/Sg5W8/

like image 180
Mr.T.K Avatar answered Oct 12 '22 10:10

Mr.T.K


Everything inside a <script> is expected to be script, not HTML.

The browser sees:

<script type="html/template" id="sample">

and starts interpreting everything that subsequently appears as script, when it reaches the inner <script its seen as just being text.

The exception to this is </script> which the browser is looking for in order to switch contexts from script to HTML, so when it sees the 1st </script> in:

<script type="text/javascript" charset="utf-8">alert('x');</script>

It assumes the opening script block is complete & switches back to expecting HTML, correctly setting the content of the outer script node to:

<script type="text/javascript" charset="utf-8">alert('x');

You can either implement what your trying to do on the server and parsing there, or use a different approach to templating.

like image 38
Alex K. Avatar answered Oct 12 '22 11:10

Alex K.