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'
. Basicly, this is the code:
document.body.innerHTML = '<div id="myDiv"><div>'
let myContainer = document.querySelector("#myDiv");
myContainer.innerHTML = '<h1>Test</h1>';
Amazingly, it still works when typescripts compiles, but I'm wondering if typescript is giving me an error, what's the right way to go on assigning innerHTML in this case?
Use a type assertion to placate the compiler:
let myContainer = <HTMLElement> document.querySelector("#myDiv");
myContainer.innerHTML = '<h1>Test</h1>';
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With