Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid typescript error: Property 'innerHTML' does not exist on type 'Element'

Tags:

typescript

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?

like image 984
Ivan Avatar asked Feb 07 '16 11:02

Ivan


4 Answers

Use a type assertion to placate the compiler:

let myContainer = <HTMLElement> document.querySelector("#myDiv");
myContainer.innerHTML = '<h1>Test</h1>';
like image 129
Vadim Macagon Avatar answered Nov 20 '22 13:11

Vadim Macagon


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)
  • https://github.com/Microsoft/TSJS-lib-generator/pull/35 (merged already)
like image 12
Martin Vseticka Avatar answered Nov 20 '22 14:11

Martin Vseticka


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;
like image 7
Ariel Massillo Avatar answered Nov 20 '22 14:11

Ariel Massillo


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.

like image 4
Karol Majewski Avatar answered Nov 20 '22 12:11

Karol Majewski