Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

javascript - Get HTMLElement from Element

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

For example:

<a href="">A link</a>
<a href="">Another link</a>

I then get them like so:

var nodes: NodeListOf<Element> = document.querySelectorAll('a'); // Returns a NodeList of Elements
for (let i = 0; i < nodes.length; i++) {
    var node = nodes.item(i);
    // How can I get the HTMLElement here?
}

Edit

enter image description here

Here is the code:

let nodes: NodeListOf<Element> = document.querySelectorAll('a');
for (let i = 0; nodes[i]; i++) {
    let node = nodes[i];
    var c = nodes[i].style.backgroundColor = 'red';
}
question from:https://stackoverflow.com/questions/38234810/get-htmlelement-from-element

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...