Question

I want to know if the variable myVar is a node.

I could check myVar.nodeType, but then I could be fooled by {nodeType:1}

Then, I wonder if I can do something like

myVar instanceof Node

Edit

Funny, it seems that there is a Node constructor, so instanceof Node works, indeed!

I should have tried if my guess worked before asking...


Please don't mark my question as a duplicate of Check if variable is a valid node element, because this other question assumes that myVar is a node or is empty. But my question doesn't assume anything.

Was it helpful?

Solution

Try window.document instanceof Node in different browsers. It returns true in IE11, GC30, FF24 and Opera17 so it should work for other Nodes, too.

In older browsers like IE8, the Node interface is undefined. I tested a couple of interfaces like HTMLDivElement for div nodes, but these are too specific, so one would have to || them into a very long logical expression. The most general interface that works in IE8 is Element: window.document.body and its child nodes are instances of Element. Interestingly, window.document is not an Element (it's an HTMLDocument).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top