typescript add an html element to an existing html document

I'm experimenting with creating a dynamic HTML element using TypeScript to display on a webpage.

In my .ts file, my code looks like this:

const displayContent = document.getElementById("display-content") as HTMLOutputElement;

var displayVariable = "";

videoArr.forEach(data => {
    displayVariable += "<h1>"+data.title + "</h1>"+"<p>"+data.description +"</p><hr/><br/>";
});
displayContent.textContent = displayVariable;

In my HTML file, I have: <div id="display-content"></div>

However, the output is not what I expected:

<h1>Book 1 Water</h1><p>Learn the water bending</p><hr/><br/><h1>Book 2 Earth</h1><p>Learn the earth bending</p><hr/><br/><h1>Book 3 Fire</h1><p>Learn the fire bending</p><hr/><br/>

It seems to display the HTML code instead of rendering the DOM. Any ideas on why this is happening?

Answer №1

To display the string as HTML, make sure to utilize displayContent.innerHTML. Using textContent will only render plain text.

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

Tips for transferring a column in an array to an object field within an array

I have a piece of code where I need to pass values from the 'dataList' array into this.data object's 'labels' and 'datasets'-> data. When I try to directly set the values, I get an undefined result. So I created a var ...

Limiting the assignment of type solely based on its own type, without considering the components of the type

I have defined two distinct types: type FooId = string type BarId = string These types are used to indicate the specific type of string expected in various scenarios. Despite TypeScript's flexibility, it is still possible to perform these assignment ...

Typescript's way of mocking fetch for testing purposes

I have a query regarding the following code snippet: import useCountry from './useCountry'; import { renderHook } from '@testing-library/react-hooks'; import { enableFetchMocks } from 'jest-fetch-mock'; enableFetchMocks(); i ...

Module not found in Typescript

Filter.ts, mustache.js and redux.3.5.2.js are all located in the same directory (/Scripts). The code snippet within Filter.ts is as follows: ///<reference path="./typings/mustache.d.ts" /> import Mustache = require("mustache"); import Redux = requir ...

Click on a link to open it in the current tab with customized headers

In my Angular project, I am attempting to open a link by clicking a button that redirects to the specified URL using the following code: window.open(MY_LINK, "_self"); However, in this scenario, I also need to include an access token in the header when t ...

How to display an [object HTMLElement] using Angular

Imagine you have a dynamically created variable in HTML and you want to print it out with the new HTML syntax. However, you are unsure of how to do so. If you tried printing the variable directly in the HTML, it would simply display as text. This is the ...

Is it possible for Next.js to retrieve the window size without resorting to a faulty hook call or encountering an undefined window

In my ongoing efforts to dynamically adjust the size of an image within a next.js application to make it responsive to various screen sizes, I have encountered challenges. The different methods I have attempted and observed have resulted in either an inv ...

I want to know the best way to send latitude and longitude coordinates from an external source in order to generate a

Looking for advice on customizing a working code that uses leaflet angular to place markers with predefined latitudes and longitudes. I want to be able to customize this by passing latitudes and longitudes when the addmarker button is pr ...

I am encountering an issue with my code where the function this.ProductDataService.getAllProducts is not recognized when

Encountering an issue while running unit test cases with jasmine-karma in Angular 7. The error received is: ProjectManagementComponent should use the ProjectList from the service TypeError: this.ProjectManagementService.getProject is not a function If I ...

What could be causing my select value to stay unchanged? Issue with the "selected" attribute or property

var original_role = $('option:selected', '#user_role').val(); $('#role_cancel').click(function() { //console.log(original_role); $('option:selected', '#user_role').removeAttr('selected'); //des ...

Module not found: vueform.config

For my current project, I decided to integrate Vueforms into the codebase. However, when I pasted their installation code into both my .ts and .js files, I encountered errors during the import of vueformconfig and builderconfig. This is a snippet of my ma ...

Access to the server has been restricted due to CORS policy blocking: No 'Access-Control-Allow-Origin'

I’m currently encountering an issue with displaying API content in Angular and I’m at a loss on how to troubleshoot it and move forward. At this moment, my main objective is to simply view the URL data on my interface. Does anyone have any insights or ...

Effective strategies for extracting value from asynchronous Angular events that return Promises

When it comes to subscription blocks, extracting the value from my API is possible. var data = null; this._timinServiceProxy.getDateFromNTP().subscribe(result => { data = result; console.log(data); // The expected result }); console.log(data); ...

Can child directives in Angular 2 harness the power of parent providers?

I am facing an issue while trying to utilize a service as a provider for general use in a Directive rather than a Component. The problem arises when the service is not being received in the child Directive, despite my expectation to use it within the direc ...

What is the reason behind Ramda having multiple curry functions in its source code, much like Redux having multiple compose functions?

There are _curry1, _curry2, _curry3, and _curryN functions within the depths of Ramda's source code This interesting pattern is also utilized in the redux compose function I find myself pondering: why did they choose this intricate pattern over a mo ...

Restricting a generic parameter to a combination type in Typescript

Is there a method in Typescript to restrict a generic parameter to only accept a union type? To clarify my question, I wish that T extends UnionType would serve this purpose: function doSomethingWithUnion<T extends UnionType>(val: T) {} doSomethingW ...

Troubleshooting Vue 2 TypeScript Components Import Issue in VS Code

Has anyone experienced issues with TS pointing errors when importing custom components into a .vue file using the options api and webpack? The import is successful, everything works after bundling, but I'm still encountering annoying errors in the .vu ...

Ways to develop a dynamic Promise-returning Function

I find myself in a situation where I am aware of the type of data that will be returned when making a request to an API. Here is the function I have: const fetchData = async (url: string, options?: Object): Promise<any> => { const res = await f ...

The issue with zone.js remains unresolved

Since updating to the most recent version of Angular cli, I have encountered an error when trying to run ng serve: ./node_modules/@angular-devkit/build-angular/src/webpack/es5-polyfills.js:106:0-37 - Error: Module not found: Error: Can't resolve &apo ...

Is it possible to invoke JavaScript code from TypeScript?

I'm struggling with calling a JavaScript file from TypeScript. After resolving one import issue and adjusting the base function for tsc recognition, I'm now stuck on recognizing a declared function prototype in the JavaScript file. Although I ha ...