Home > Web Front-end > JS Tutorial > body text

How to determine whether a js object is a dom object

高洛峰
Release: 2016-12-05 14:32:21
Original
1309 people have browsed it

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 === &#39;object&#39; ) ?
        function(obj){
          return obj instanceof HTMLElement;
        } :
        function(obj){
          return obj && typeof obj === &#39;object&#39; && obj.nodeType === 1 && typeof obj.nodeName === &#39;string&#39;;
        }
  </script>
Copy after login


Related labels:
js
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!