Skip to content
Advertisement

How to display a script tag with json content in a code block in html?

I want to display a chunk of code generated dynamically inside a code example block that users can highlight a copy.

The content will change based on user input so it cannot be hardcoded.

This is an example of the content I would like to display inside the block:

<script type="application/ld+json">{
  "name": "PBOV1 Is a Human De Novo Gene with Tumor-Specific Expression That Is Associated with a Positive Clinical Outcome of Cancer",
  "keywords": "pbov1, tumor-specific, cancer, Cancer, Evolutionary Biology, Immunology",
  "version": "1",
  "url": "https://figshare.com/articles/PBOV1_Is_a_Human_De_Novo_Gene_with_Tumor_Specific_Expression_That_Is_Associated_with_a_Positive_Clinical_Outcome_of_Cancer__/156778",
  "license": ""
}</script>

I’m using VueJS and this is the method in progress:

makeScript(){
  var str = JSON.stringify(this.metadata, null, 2);
  var script=document.createElement('script');
  script.type='application/ld+json';
  script.text = str;
  this.result = script;
  document.getElementById("resultCode").appendChild(script);
},

I’ve tried “code” and “pre” and all it shows is nothing but the script is there. I think the script is getting compiled and not shown as text, I could be wrong…. I hope that makes sense.

output goes here:

<div class="form-group">
  <pre >
    <code id="resultCode">
    </code>
  </pre>
</div>

Advertisement

Answer

  1. Construct the script element.
  2. Put it in a new, temporary element.
  3. Put the innerHTML of the temp element into a text node.
  4. Put that text node into the output element.

function makeScript() {
  metadata = {
    "name": "PBOV1 Is a Human De Novo Gene with Tumor-Specific Expression That Is Associated with a Positive Clinical Outcome of Cancer",
    "keywords": "pbov1, tumor-specific, cancer, Cancer, Evolutionary Biology, Immunology",
    "version": "1",
    "url": "https://figshare.com/articles/PBOV1_Is_a_Human_De_Novo_Gene_with_Tumor_Specific_Expression_That_Is_Associated_with_a_Positive_Clinical_Outcome_of_Cancer__/156778",
    "license": ""
  }
  var str = JSON.stringify(metadata, null, 2);
  var script = document.createElement('script');
  script.type = 'application/ld+json';
  script.text = str;
  
  p = document.createElement('div');
  p.appendChild(script);
  text = document.createTextNode(p.innerHTML);
  
  document.getElementById("resultCode").appendChild(text);
}

makeScript();
<div class="form-group">
  <pre><code id="resultCode"></code></pre>
</div>
Advertisement