typescript 从元素中获取 HTMLElement
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38234810/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get HTMLElement from Element
提问by Get Off My Lawn
I have an Element
, and I can not figure out how to get the HTMLElement
from it.
我有一个Element
,我不知道如何从中获取HTMLElement
。
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
编辑
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';
}
回答by Nitzan Tomer
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.
问题是document.querySelectorAll
返回最通用的元素类型,但是如果您知道自己的具体类型是什么,那么您可以进行转换,因为您比编译器“更了解”。
回答by Erik Engervall
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";
}
回答by Get Off My Lawn
The way that works, is to cast the element to an HTMLElement
.
有效的方法是将元素强制转换为HTMLElement
.
let nodes: NodeListOf<HTMLElement> = document.querySelectorAll('a') as NodeListOf<HTMLElement>;