日期:2014-05-17  浏览次数:20621 次

判断元素是否为HTMLElement元素【转载】

地址:http://www.cnblogs.com/snandy/archive/2011/03/12/1981516.html

我们经常使用nodeType==1判断元素是否是一个HMTLElement元素。页面上的元素都是节点(Node),有元素节点(Element Node)、属性节点(Attribute Node)、文本节点(Text Node)等。w3c nodeType 的定义如下

const unsigned short ELEMENT_NODE = 1;
const unsigned short ATTRIBUTE_NODE = 2;
const unsigned short TEXT_NODE = 3;
const unsigned short CDATA_SECTION_NODE = 4;
const unsigned short ENTITY_REFERENCE_NODE = 5;
const unsigned short ENTITY_NODE = 6;
const unsigned short PROCESSING_INSTRUCTION_NODE = 7;
const unsigned short COMMENT_NODE = 8;
const unsigned short DOCUMENT_NODE = 9;
const unsigned short DOCUMENT_TYPE_NODE = 10;
const unsigned short DOCUMENT_FRAGMENT_NODE = 11;
const unsigned short NOTATION_NODE = 12;

?

但如果我们自定义的对象也包含nodeType属性呢?如

view sourceprint?
1 var obj = {nodeType:1};
2 function isHTMLElement(obj){
3 ????if(obj.nodeType){
4 ????????return obj.nodeType==1;
5 ????}
6 }
7 isHTMLElement(obj);//true

以上isHTMLElement(obj)返回true,但obj明显不是一个HTML节点元素。下面通过对象特性及try-catch语句来判断。

view sourceprint?
01 function isHTMLElement(obj){