1

I am trying to format JavaScript code snippet to display on a web page as follow:-

<pre class="prettyprint">
     <code class="javascript"><script> $(document).ready(function(){ setTimeout(function(){ console.log('deleting cookie'); $.cookie('cookie',null,{domain: document.domain}); },1000); }); </script></code>
  </pre>

I got the clue from this SO Link.

I have included all the files and followed the instrucntion but its not formatting it rather showing the snippet as combined.

Here is a screen shot enter image description here

I am getting the code from json file that is why it is in a single line.

I have removed the <script> and the result is same.

<pre class="prettyprint">
         <code class="javascript">$(document).ready(function(){ setTimeout(function(){ console.log('deleting cookie'); $.cookie('cookie',null,{domain: document.domain}); },1000); });</code>
      </pre>

Any clue how may I intend it properly ?

2
  • 2
    1: this is real script, so it will run, it is not inert text. 2: did you remember to set the CSS for script { display: block; } or something? Because script elements are not shown by default, for obvious reasons. Commented Jan 1, 2019 at 16:53
  • @ MikePomax I have removed the script tag still its the same. Commented Jan 1, 2019 at 16:55

1 Answer 1

0

If you wish to show the indents, you need to format the content in a multi-line string.

document.getElementById('src').textContent = 
`
$(document).ready(function(){ 
   setTimeout(function(){ 
      console.log('deleting cookie'); 
      $.cookie('cookie',null,{domain: document.domain}); 
   },1000); });
`;
<pre class="prettyprint">
     <code class="javascript" id="src"></code>
</pre>

BTW, please do not use document.getElementById('src').innerHTML = xxx, since <script> inside the string would be valid javascript code and would be executed

Sign up to request clarification or add additional context in comments.

2 Comments

I am reading it from json file and cannot do it in a multi line.
I don't think the google's code prettify supports auto-indent or auto-format the code, which is going to be too heavy, since there are too many programming languages to cover...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.