Get HTMLElement from Element

Hey! It may be dumb? Idk. Anyways, I got an Element object from document.querySelector(), tho what I need to suit my needs is an HTMLElement. And when doing ↓
if (element !instanceof HTMLElement) return;
if (element !instanceof HTMLElement) return;
Typescript doesn't consider element as an HTMLElement in the code after that if . I know why, but I don't know how to do otherwise so... Asking here :p
Solution:
querySelector() either returns nothing or a dom element. if it does not return an element you can simply use ```ts const el = document.querySelector("#element") if (!el) { return...
Jump to solution
3 Replies
@TheFriendsOfOwlsAndTitans
I mean I could force Typescript into thinking it is (which it is) with as HTMLElement or <HTMLElement> but I don't really know if it's the most typesafe way to do it you know
Solution
__sifatul__
__sifatul__11mo ago
querySelector() either returns nothing or a dom element. if it does not return an element you can simply use
const el = document.querySelector("#element")
if (!el) {
return
}
const el = document.querySelector("#element")
if (!el) {
return
}
you can then return the element by telling the typescript what it is
return el as ButtonElement
return el as ButtonElement
or retunr the element as HTMLElement.
@TheFriendsOfOwlsAndTitans
okay thanks!

Did you find this page helpful?