从Element获取HTMLElement [英] Get HTMLElement from Element

查看:1195
本文介绍了从Element获取HTMLElement的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有元素,我无法弄清楚如何从中获取 HTMLElement

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

例如:

<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?
}

修改

以下是代码:

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';
}


推荐答案

你只需要投下它:

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';

事情是 document.querySelectorAll 返回最通用的元素类型,但是如果你知道自己什么是特定的类型那么你可以强制转换,因为你比编译器知道更好。

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.

这篇关于从Element获取HTMLElement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆