Home >Web Front-end >JS Tutorial >How to determine whether a js object is a dom object
When we write js code, we sometimes need to determine whether an object is a DOM object before performing subsequent operations. Here I will give you a method that is compatible with major browsers and is relatively safe.
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 a DOM object, such as whether it has a nodeType attribute, a tagName attribute, etc. The more features that are judged, the more reliable it is, because after all, our custom js objects can also have those attributes. Are there other methods?
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"> //首先要对HTMLElement进行类型检查,因为即使在支持HTMLElement //的浏览器中,类型却是有差别的,在Chrome,Opera中HTMLElement的 //类型为function,此时就不能用它来判断了 var isDOM = ( typeof HTMLElement === 'object' ) ? function(obj){ return obj instanceof HTMLElement; } : function(obj){ return obj && typeof obj === 'object' && obj.nodeType === 1 && typeof obj.nodeName === 'string'; } </script>