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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.