最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Converting Element to HTMLElement in javascripttypescript - Stack Overflow

programmeradmin1浏览0评论

So, I'm getting a list of elements that match a selector using querySelectorAll, which stores them in a NodeList.

I'm then scanning through the NodeList with a forEach loop, at which point the type of each individualItem is "Element".

However, I'm feeding these individualItems into a function "doThing()" that expects individualItem to be of type "HTMLElement" (I'm using typescript). I'm wondering if there is some built in js function for converting an "Element" type into an "HTMLElement" type, or, if not, what a function like that might looks like

const h = document.querySelectorAll(someClassString);

h.forEach(individualItem => {
            individualItem.addEventListener(c.EVENT, () => doThing(individualItem));
})    

So, I'm getting a list of elements that match a selector using querySelectorAll, which stores them in a NodeList.

I'm then scanning through the NodeList with a forEach loop, at which point the type of each individualItem is "Element".

However, I'm feeding these individualItems into a function "doThing()" that expects individualItem to be of type "HTMLElement" (I'm using typescript). I'm wondering if there is some built in js function for converting an "Element" type into an "HTMLElement" type, or, if not, what a function like that might looks like

const h = document.querySelectorAll(someClassString);

h.forEach(individualItem => {
            individualItem.addEventListener(c.EVENT, () => doThing(individualItem));
})    

Share Improve this question asked Feb 12, 2020 at 20:35 LukeLuke 1,8303 gold badges17 silver badges34 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 11

To type the output from querySelectorAll you can do it this way:

document.querySelectorAll<HTMLTableElement>('.mytable')

Since you are using TypeScript, why don't you cast it to another type? See it here

const h = document.querySelectorAll(someClassString);

h.forEach(individualItem => {
    individualItem.addEventListener(c.EVENT, () => doThing(individualItem as HTMLElement));
});

EDIT 2023

I don't know if I had a limited knowledge of Typescript when I wrote this or if this functionality wasn't available yet, but as Ron Jonk pointed out, the most elegant and reusable solution is

const h = document.querySelectorAll<HTMLElement>(someClassString);

h.forEach(individualItem => {
    individualItem.addEventListener(c.EVENT, () => doThing(individualItem));
});
发布评论

评论列表(0)

  1. 暂无评论