user2753924
user2753924

Reputation: 465

Display javascript code with text()

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?

Upvotes: 1

Views: 738

Answers (1)

Alex Tartan
Alex Tartan

Reputation: 6836

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()?

Upvotes: 2

Related Questions