How to determine whether a JS object is a DOM object _javascript tips

Source: Internet
Author: User

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 ~

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.