Frage

I am looking for a way to get all the children HTMLElement of an HTMLElement in javascript. I used childNodes but I am having trouble casting a NodeList to an Array.<HTMLElement> as they are not subtypes of each other (I am using Google Closure Compiler to enforce typing).

Here is an example that returns a warning:

/** @type {Array.<HTMLElement>} */
var kids = /** @type {Array.<HTMLElement>} */ (document.childNodes);

It 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);
                                               ^

As all childNodes are not HTMLElements I can understand the warning but is there a work around?

=== EDIT ===

Surprisingly, I am having no problem casting a Node to an HTMLElement. The problem comes from casting a NodeList to an Array.<Node>.

War es hilfreich?

Lösung

I believe that the compiler is correct in this case - NodeLists are not Arrays nor are they even related. See https://developer.mozilla.org/en-US/docs/Web/API/NodeList

You need to augment your type definition with a union of both types:

/** @type {Array.<Node>|NodeList} */
var kids = document.childNodes;
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top