怎么判断元素是否为HTMLElement元素,本文通过对象特性及try-catch语句来判断。
我们经常使用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){
02 var d = document.createElement("div");
03 try{
04 d.appendChild(obj.cloneNode(true));
05 return obj.nodeType==1?true:false;
06 }catch(e){
07 return false;
08 }
09 }
10 var obj1 = {nodeType:1};
11 var obj2 = document.createTextNode("hello");
12 var obj2 = document.createElement("p");
13 isHTMLElement(obj1);//false
14 isHTMLElement(obj2);//false
15 isHTMLElement(obj3);//true
对于window和document还要特别处理下
view sourceprint?
01 function isHtmlControl(obj) {
02
03 var d = document.createElement("div");
04 try{
05 d.appendChild(obj.cloneNode(true));
06 return obj.nodeType==1 ? true : false;
07 }catch(e){
08 return obj==window || obj==document;
09 }
10 }