简体   繁体   中英

class with html element property

I want to create a class which has the div element as a property

<div id="corpus"></div>


class ProtoDiv {
    divElement: HTMLDivElement;

    constructor(){
        this.divElement = <HTMLDivElement>document.getElementById("corpus")!;

    }

    getDivElem(this:ProtoDiv){
        console.log(this.divElement)
    }
    
}

const myDiv = new ProtoDiv();

console.log(myDiv.divElement);


why does the property returns null instead of the html div element?

Your code totally works as plain JavaScript (I've just pasted the result of TypeScript transpilation). You must be missing something like the script execution order (does the div exist when the code execute?).

 "use strict"; class ProtoDiv { constructor() { this.divElement = document.getElementById("corpus"); } getDivElem() { console.log(this.divElement); } } const myDiv = new ProtoDiv(); console.log(myDiv.divElement);
 <div id="corpus"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM