When writing js code, we sometimes need to determine whether an object is a DOM object, and then perform subsequent operations. Here I will give a relatively safe method that is compatible with major browsers.
To determine whether an object is a DOM object, the first thing that comes to mind is whether it has various attributes or characteristics of the DOM object, such as whether it has nodeType attribute, tagName attribute, etc. The more characteristics you judge, the more reliable it is, because after all, our customized js objects can also have those properties. Is there any other way?
An HTMLElement object is defined in the DOM Level2 standard, which stipulates that all DOM objects are instances of HTMLElement, so we can use this to determine whether an object is a DOM object: if the object is an instance of HTMLElement, it must be a DOM object. In browsers that do not support HTMLElement, we still use feature detection.
<script type="text/javascript"> //First type checking of HTMLElement is required, because even if HTMLElement is supported, //The types are different in the browser. In Chrome and Opera, HTMLElement //The type is function, so you can't use it to judge at this time var isDOM = ( typeof HTMLElement === 'object' ) ? function(obj){ return obj instanceof HTMLElement; } : function(obj){ return obj && typeof obj === 'object' && === 1 && typeof === 'string'; } </script>
The above is all the contents of how to determine whether a js object is a dom object, I hope everyone supports me~