TypeScript: casting HTMLElement

后端 未结 13 2313
我寻月下人不归
我寻月下人不归 2020-12-02 05:34

Does anyone know how to cast in TypeScript?

I\'m trying to do this:

var script:HTMLScriptElement = document.getElementsByName(\"script\")[0];
alert(s         


        
13条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-02 05:44

    Since it's a NodeList, not an Array, you shouldn't really be using brackets or casting to Array. The property way to get the first node is:

    document.getElementsByName(id).item(0)
    

    You can just cast that:

    var script =  document.getElementsByName(id).item(0)
    

    Or, extend NodeList:

    interface HTMLScriptElementNodeList extends NodeList
    {
        item(index: number): HTMLScriptElement;
    }
    var scripts =  document.getElementsByName('script'),
        script = scripts.item(0);
    

提交回复
热议问题