Right now I am using isElement
by lodash to check if an element is DOM likely. I want to get rid of this library so I am looking for a pure JS implementation of this function.
I'm using this, but I don't know if it's the right implementation and if I'm ignoring any edge cases:
const isDOMElement = el => el instanceof HTMLElement
Update
I have tested (codepen link) the four proposed implementation, in all cases is working as expected, maybe the one proposed by @cesare covers most of the cases, but also the one proposed by @peter-seliger is clever and work with an "outside of the BOX" thinking. Finally, both @David Thomas and the one I firstly use, works for most of the cases.
So in conclusion I think, as David Thomas points It's just a matter of preference
.
P.S: The tags used for the test are extracted from MDN's HTML elements reference
P.S2: Not sure on how to proceed and what answer accept. Both cesare and peter have a good point
This is the
lodash
util:Basically with
isObjectLike
it checks that the value passed is a nonnull
object ( since null is an object in js ) and with!isPlainObject
that it is not a plain object ( since it could be an object carrying a "nodeType": 1 entry and because an HTMLElement instance has nested protos.The
isPlainObject
util is this:As you can see the first check is redundant since it checks
isObjectLike
again, but the main caveat in my opinion is that it doesn't cover other objects case, since for example "Arrays" are objects too hence they pass the check:Try it yourself.
I think it's safer to check if the object has a
nodeType
property that is inherited:In any case I prefer using your check which already covers most of those checks since any primitive non object is not instance of HTMLElement, null is not instance of HTMLElement, and an HTMLElement instance has a "nodeType" poperty but it is inherited from proto and not an own property, :