1

I'm trying to display some javascript within pre/code tags using jQuery text() method. Like this:

 jQuery(".output").wrapInner( "<pre><code></code></pre>" );
 jQuery(".output code").text("<script type='text/javascript' src='http://somedomain/?" + apiKeyValue.val() + "></script>");

However the script tags produce a

Uncaught SyntaxError: Unexpected token ILLEGAL

error in the console. How can I display the script tags?

Blake Yarbrough
  • 2,286
  • 1
  • 20
  • 36
user2753924
  • 465
  • 1
  • 5
  • 15

1 Answers1

2

Replace

jQuery(".output code").text("<script type='text/javascript' src='http://somedomain/?" + apiKeyValue.val() + "></script>");

with:

jQuery(".output code").text("<script type='text/javascript' src='http://somedomain/?" + apiKeyValue.val() + "></"+"script>");

or:

jQuery(".output code").text("<script type='text/javascript' src='http://somedomain/?" + apiKeyValue.val() + "><\/script>");

You need to break the </script> tag ("</"+"script>") or escape the / ("<\/script>")

As pointed out by TreeTree in the comment, for a detailed explanation, please read Why split the <script> tag when writing it with document.write()?

Community
  • 1
  • 1
Alex Tartan
  • 6,736
  • 10
  • 34
  • 45
  • I think you also need to replace `text(".....")` with `text('.....')` as `html attributes` is better to be quoted with `" "` like `type="text/javascript"` – Guruprasad J Rao Jul 17 '15 at 16:57
  • I think an explanation of why you have to do this would go a long way. I found this http://stackoverflow.com/questions/236073/why-split-the-script-tag-when-writing-it-with-document-write. – TreeTree Jul 17 '15 at 16:59