Enriching HtmlElement with a type property using TypeScript

Check out my TypeScript code snippet below:

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

But I encountered a specific error:

Uncaught SyntaxError: Unexpected token :

I suspect this error is caused by the missing type property with the value of application/json in the HTMLElement variable. This issue arises when trying to append it to the body.

My goal is to find a way to incorporate the type="application/json" property into the script element using only TypeScript.

Answer №1

If you want to add an attribute to an HTMLElment, all you need to do is use the setAttribute function that belongs to the element:

let newElement: HTMLElement = document.createElement("newElement");
newElement.appendChild(document.createTextNode(`
  {
    "json": "attribute"
  }
`));
newElement.id = 'uniqueID';
newElement.setAttribute('customAttribute', 'example');
document.body.appendChild(newElement);

Alternatively, you can simply update the attribute like this:

newElement.customAttribute = 'example';

Remember to be cautious about security considerations when inserting code directly into a newElement, especially if it's based on user input.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Refresh a Google chart without having to reload the entire page

I currently have a button that allows me to refresh the data on my page in case there is new data available through an API. Although this button successfully refreshes my datatable, it does not redraw the Google charts I have integrated into my project usi ...

Is it necessary to use Generics in order for a TypeScript `extends` conditional type statement to function properly?

Looking to improve my understanding of the extends keyword in TypeScript and its various uses. I recently discovered two built-in utilities, Extract and Exclude, which utilize both extends and Conditional Typing. /** * Exclude from T those types that are ...

The issue of Angular 6 view failing to display accurate data upon page load

In my Angular 6 application, I've implemented a login feature using Firebase's Google login. The interface includes a button labeled Login when the user is logged out, and changes to Logout with the current email address displayed when the user i ...

There was a mistake: _v.context.$implicit.toggle cannot be used as a function

Exploring a basic recursive Treeview feature in angular4 with the code provided below. However, encountering an error when trying to expand the child view using toggle(). Encountering this exception error: ERROR TypeError: _v.context.$implicit.toggle i ...

The ASP.NET Core Web API is designed to handle incoming dates that are one day in the past, as sent by

After selecting a date from an Angular material datepicker, the ASP.NET Core Web API consistently receives the date as one day earlier. The date being sent is obtained from a form control and assigned to a property like so: scheme.date1 = this.formControl ...

Old version of Nativescript appium testing being installed ORAn outdated

I am in the process of creating a mobile application using nativescript + angular, and I am currently testing it with Appium. However, when I execute end-to-end tests using the following command, it seems to load an older version of my app. tns build andr ...

Rendering illuminated component with continuous asynchronous updates

My task involves displaying a list of items using lit components. Each item in the list consists of a known name and an asynchronously fetched value. Situation Overview: A generic component named simple-list is required to render any pairs of name and va ...

Unable to capture Metamask Errors

I am attempting to invoke a smart contract using ethers.contract and the signer from ethers.providers.web3Provider to leverage MetaMask. If the transaction fails, I want to capture the error and either retry or invoke a different function. However, my proj ...

The element type 'x' in JSX does not offer any construct or call signatures

I have recently imported an image and I am trying to use it within a function. The imported image is as follows: import Edit from 'src/assets/setting/advertising/edit.png'; This is the function in question: function getOptions(row) { ...

Typescript-powered React component for controlling flow in applications

Utilizing a Control flow component in React allows for rendering based on conditions: The component will display its children if the condition evaluates to true, If the condition is false, it will render null or a specified fallback element. Description ...

Tips for identifying two mat-tables within the same component in Angular UI

Having trouble with rendering rows in two mat-tables within the same component. The renderRows() function is not working for the second table. @ViewChild(MatTable) tagsTable: any; @ViewChild(MatTable) serviceAreaTable:any; this.tagsTable.renderRows(); # ...

Creating a unique type with a suffix of `px`

Understanding how to create a Position type class is clear: class Position { x: number = 0; y: number = 0; } However, I now require the x and y values to be integers with the suffix of px, like this: const position = { x: '1px', y: &ap ...

IE11 does not support Angular2 Final

After working for a period of time, my implementation suddenly stopped. It seems that I may have imported a component or made some other change causing the issue. Strangely enough, it functions properly on Firefox, Chrome, and Edge, but encounters an error ...

Using TypeScript, add an observable to an array of observables using RxJS

Can someone explain how to include Observable<News> in an array of observables? newsArray: Observable<Array<any>>; addNews(newsId: number) { let news = this.newsService.getNewNews(newsId); // this results in an Observable<News> ...

Alert: TypeScript Linter Warning

When I execute the npm lint command in Circle CI, a warning message is displayed. The following rules specified in the configuration could not be found: templates-use-public no-access-missing-member invoke-injectable template-to-ng-templa ...

Executing the ngIf directive in Angular 2 when a function or click event occurs

Is there a way to display an element only when a specific function is executed or a particular click event occurs? Here's the html code snippet I'm currently working with: <sebm-google-map [latitude]="lat" [longitude]="lng" [zoom]="zoom" [map ...

How to retrieve the value of a nested checkbox in Angular using dynamic methods

I successfully developed dynamic nested checkboxes in Angular and now I am looking to retrieve the values of the selected checkboxes. However, I encountered an issue with the JSON structure needed to implement this functionality. https://i.stack.imgur.com ...

Angular array of considerable size

Dealing with a massive array of 30,000 items can be quite daunting, especially when it comes in as a stream using grpc-web. Currently, I'm fetching the data from grpc.client() and populating an array before displaying it using *ngFor. However, I' ...

Adding an external JavaScript library file to a specific component in Angular 7 is a straightforward process. Let's walk through the

As a beginner in Angular framework, I've encountered an issue while working on creating a custom HTML template using Angular version 7. My template consists of various pages like home, about, product, etc. Specifically, on the home page, I am trying t ...

Angular - Ensure completion of a function call before continuing with the code execution

I'm currently working on developing a code snippet that checks for potential adverse drug reactions between two medications. Within my checkForClash() function, there is a call to getCollisionsList(), which is responsible for populating the interacti ...