Casting a NodeList into an array. <HTMLElement> in javascript
I am looking for a way to get all HTMLElement
children from HTMLElement
in javascript. I used childNodes
, but it's hard for me to send a NodeList
to Array.<HTMLElement>
, because they are not subtypes of each other (I use the Google Closure compiler to force text input).
Here is an example that returns a warning:
/** @type {Array.<HTMLElement>} */ var kids = /** @type {Array.<HTMLElement>} */ (document.childNodes);
He returns
test.js:2: WARNING - invalid cast - must be a subtype or supertype from: NodeList to : (Array.<(HTMLElement|null)>|null) var kids = /** @type {Array.<HTMLElement>} */ (document.childNodes); ^
Since all childNodes
not HTMLElements
, I can understand the warning, but is there any work around?
=== EDIT ===
Surprisingly, I have no problem casting Node
in HTMLElement
. The problem is due to casting NodeList
in Array.<Node>
.
I believe that the compiler is right in this case - NodeLists are not arrays and are not even related. See https://developer.mozilla.org/en-US/docs/Web/API/NodeList
You need to increase the type definition by combining both types:
/** @type {Array.<Node>|NodeList} */ var kids = document.childNodes;