When we write JS code sometimes need to determine whether an object is not a DOM object, and then follow the operation, here I give a compatible with the major browsers, but also a more secure way.
To determine whether an object is a DOM object, the first thing to think about is whether it has a variety of properties or features of a DOM object, such as whether there are NodeType properties, tagname properties, and so on. The more characteristics of judgment, the more reliable, because after all, our custom JS object can also have those attributes. Is there any other way?
A 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, Then it must be a DOM object. We still use feature detection in browsers that do not support htmlelement.
<script type= "Text/javascript" >
//First type check for HtmlElement, because the type is different even in browsers that support HtmlElement//
. In Chrome,opera htmlelement
//Type is a function, it can not be used to determine the
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>
The above is a small series for everyone how to determine whether a JS object is a DOM object all content, I hope that we support cloud Habitat Community ~