I\'m trying to place some HTML inside a specific div. When I try this in typescript I get this error: Property \'innerHTML\' does not exist on type \'Element\'
Use like this (<HTMLElement>document.querySelector("#myDiv")).innerHTML
In future versions of TypeScript, it should not be necessary to do the casting. I've sent a pull request to fix the issue:
error: Property 'innnerHTML' does not exist on type 'Element'
(https://github.com/Microsoft/TypeScript/issues/5754)I had the same issue, solved it by declaring it as:
myString = 'hello world';
var el: HTMLElement = document.getElementById('id_of_element');
el.innerHTML = myString;
Use a type assertion to placate the compiler:
let myContainer = <HTMLElement> document.querySelector("#myDiv");
myContainer.innerHTML = '<h1>Test</h1>';
let myContainer = document.querySelector("#myDiv") as HTMLElement;
let myContainer = document.querySelector("#myDiv");
let myContainer : HTMLElement = document.querySelector("#myDiv");
Parse your element like this and you should be able to insert whatever you want in it.
The only type-safe way to modify DOM elements is to verify they exist first. TypeScript is smart enough to tell you that document.querySelector
can return null
when the target is not found in the document.
document.body.innerHTML = '<div id="myDiv"><div>'
let myContainer: HTMLDivElement | null = document.querySelector("#myDiv");
if (myContainer instanceof HTMLDivElement) {
myContainer.innerHTML = '<h1>Test</h1>';
}
The above code compiles without error in TypeScript 3.2.1.