TypeScript: casting HTMLElement

后端 未结 13 2287
我寻月下人不归
我寻月下人不归 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

    To end up with:

    • an actual Array object (not a NodeList dressed up as an Array)
    • a list that is guaranteed to only include HTMLElements, not Nodes force-casted to HTMLElements
    • a warm fuzzy feeling to do The Right Thing

    Try this:

    let nodeList : NodeList = document.getElementsByTagName('script');
    let elementList : Array = [];
    
    if (nodeList) {
        for (let i = 0; i < nodeList.length; i++) {
            let node : Node = nodeList[i];
    
            // Make sure it's really an Element
            if (node.nodeType == Node.ELEMENT_NODE) {
                elementList.push(node as HTMLElement);
            }
        }
    }
    

    Enjoy.

提交回复
热议问题