1

I have the following TypeScript code:

let script: HTMLElement = document.createElement("script");
script.appendChild(document.createTextNode(`
  {
    "json": "property"
  }
`));
script.id = 'appContextModel';
document.body.appendChild(script);

And I'm getting the following error:

Uncaught SyntaxError: Unexpected token :

I think because the script variable does not have the property type with value application/json when I try to append to the body that HTMLElement, the compiler is retrieving the error.

What I'm looking for is a way to add the type="application/json" property to the script element, using only TypeScript.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Ricardo Rocha
  • 14,612
  • 20
  • 74
  • 130
  • [`setAttribute`](https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute). Use that to set the `type` attribute. Note that property names must be quoted with double quotes in order to be valid JSON... – Heretic Monkey Oct 01 '18 at 11:38
  • @HereticMonkey Sorry, I change the question to be more like my real situation. The setAttribute solve my issue, so thank you for that. If you want, you can put you comment as an answer. – Ricardo Rocha Oct 01 '18 at 11:44

1 Answers1

2

To add an attribute to an HTMLElment, simply call the setAttribute function of the element:

let script: HTMLElement = document.createElement("script");
script.appendChild(document.createTextNode(`
  {
    "json": "property"
  }
`));
script.id = 'appContextModel';
script.setAttribute('type', 'application/json');
document.body.appendChild(script);

Or, in this case, just set the property:

script.type = 'application/json';

Note that there are some security issues to consider when writing code directly into a script element, especially if in response to user input.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122