-2

Possible Duplicate:
How can JavaScript make new page that contains more JavaScript?

I tried writing this: document.write('<script>document.write("test")</script>'); and it displays '); });//]]> I believe that it's because I wrote <script> </script> in it, why does it happen and what can I do (I purposely want it surrounded by <script>?

Thanks.

Community
  • 1
  • 1
user172071
  • 65
  • 1
  • 5
  • 4
    generally you should try to avoid using `document.write` at all. http://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice – evan Dec 04 '11 at 00:23

4 Answers4

3

You either have to put it in an external file (where scripts belong) or do the ugly "escaping" thing:

document.write('<script>document.write("test")</scr' + 'ipt>');

or

document.write('<script>document.write("test")<\/script>');

But really, put it in an external file, please.

Ry-
  • 199,309
  • 51
  • 404
  • 420
1

The sequence </script> … ends the script element. If you do this in the middle of a string, then you end up with a JS syntax error.

In a JS string, \/ means the same as /, so escape the slash character to avoid having an end tag in the markup.

document.write('<script>document.write("test")<\/script>'); 
Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
  • It works but it's not surrounded by script. – user172071 Dec 04 '11 at 00:25
  • 1
    If you mean you want to write the **text** ` – Quentin Dec 04 '11 at 00:26
0

It happens because the browser will see the </script> part and think it's the ending tag of your script.

To overcome this, just split it in two strings like this

'<script>document.write("test")</scr'+'ipt>'
solarc
  • 5,143
  • 2
  • 35
  • 49
0

When the browser runs your script and encounters </script> It would think your script has ended. I would have the string split up into 2 separate strings concatenated together. Or you could put your script in an external file and not run into the problem entirely. The second might be a little extra work if you're doing a small thing, but it does make it so you don't have to write anything extra or concatenate.

SemicolonExpected
  • 589
  • 1
  • 10
  • 36