If you're using TypeScript, the solution would look something like this:
const nodes = document.querySelectorAll(".link");
function isHTMLElement(node: Node): node is HTMLElement {
return node instanceof HTMLElement;
}
const onlyHTMLNodes = Array.from(nodes).filter(isHTMLElement);
If you're only using JSDoc, it'll look like this:
const nodes = document.querySelectorAll(".link");
/**
* @param {Element} node
* @returns {node is HTMLElement}
*/
function isHTMLElement(node) {
return node instanceof HTMLElement;
}
const onlyHTMLNodes = Array.from(nodes).filter(isHTMLElement);
In both cases, you'll end up with an array of HTMLElements.
node instanceof HTMLElement
is the key thing that makes this work; if you manage to query something that isn't HTML like a SVG element, that will filter it out. The node is HTMLElement
type predicate is what makes TS/JSDoc aware of what you've done.
The other answers here are okay, but either depend on implicit assignments that work just because you're querying an a
element (so it returns NodeListOf<HTMLAnchorElement>
) or use explicit type casting, which might be okay in this situation but, depending on the kind of query you're making, might stick you with a runtime error in the future.