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

后端 未结 6 1988
时光说笑
时光说笑 2020-12-16 09:14

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\'

相关标签:
6条回答
  • 2020-12-16 09:37

    Use like this (<HTMLElement>document.querySelector("#myDiv")).innerHTML

    0 讨论(0)
  • 2020-12-16 09:39

    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)
    0 讨论(0)
  • 2020-12-16 09:43

    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;
    
    0 讨论(0)
  • 2020-12-16 09:54

    Use a type assertion to placate the compiler:

    let myContainer = <HTMLElement> document.querySelector("#myDiv");
    myContainer.innerHTML = '<h1>Test</h1>';
    
    0 讨论(0)
  • 2020-12-16 09:54
    1. let myContainer = document.querySelector("#myDiv") as HTMLElement;

    2. let myContainer = document.querySelector("#myDiv");

    3. let myContainer : HTMLElement = document.querySelector("#myDiv");

    Parse your element like this and you should be able to insert whatever you want in it.

    0 讨论(0)
  • 2020-12-16 09:57

    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.

    0 讨论(0)
提交回复
热议问题