Get HTMLElement from Element

前端 未结 4 677
孤街浪徒
孤街浪徒 2021-01-07 16:58

I have an Element, and I can not figure out how to get the HTMLElement from it.

For example:

A link

        
相关标签:
4条回答
  • 2021-01-07 17:13

    You just need to cast it:

    let nodes = document.querySelectorAll('a');
    for (let i = 0; nodes[i]; i++) {
        let node = nodes[i];
        var c = (nodes[i] as HTMLElement).style.backgroundColor = 'red';
    }
    

    You can even cast to a more specific element:

    (nodes[i] as HTMLAnchorElement).style.backgroundColor = 'red';
    

    The thing is that document.querySelectorAll returns the most generic element type, but if you know yourself what is the specific type then you can cast, because you "know better" than the compiler.

    0 讨论(0)
  • 2021-01-07 17:25

    You're close!

    var nodes = document.querySelectorAll('a'); // Returns a NodeList of Elements
    for (let i = 0; nodes[i]; i++) {
        // node is your element!
        var node = nodes[i];
        node.style.backgroundColor = "blue";
    }
    
    0 讨论(0)
  • 2021-01-07 17:32

    The way that works, is to cast the element to an HTMLElement.

    let nodes: NodeListOf<HTMLElement> = document.querySelectorAll('a') as NodeListOf<HTMLElement>;
    
    0 讨论(0)
  • 2021-01-07 17:32
    let nodes = document.querySelectorAll<HTMLElement>('a');
    // or
    let nodes = document.querySelectorAll<HTMLAnchorElement>('a');
    
    0 讨论(0)
提交回复
热议问题