zl程序教程

您现在的位置是:首页 >  其它

当前栏目

如何判断元素是否为HTMLElement元素

如何 判断 是否 元素
2023-06-13 09:15:13 时间

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

constunsignedshortELEMENT_NODE=1;
constunsignedshortATTRIBUTE_NODE=2;
constunsignedshortTEXT_NODE=3;
constunsignedshortCDATA_SECTION_NODE=4;
constunsignedshortENTITY_REFERENCE_NODE=5;
constunsignedshortENTITY_NODE=6;
constunsignedshortPROCESSING_INSTRUCTION_NODE=7;
constunsignedshortCOMMENT_NODE=8;
constunsignedshortDOCUMENT_NODE=9;
constunsignedshortDOCUMENT_TYPE_NODE=10;
constunsignedshortDOCUMENT_FRAGMENT_NODE=11;
constunsignedshortNOTATION_NODE=12;


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

复制代码代码如下:

varobj={nodeType:1};
functionisHTMLElement(obj){
   if(obj.nodeType){
       returnobj.nodeType==1;
   }
}
isHTMLElement(obj);//true

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

functionisHTMLElement(obj){
   vard=document.createElement("div");
   try{
       d.appendChild(obj.cloneNode(true));
       returnobj.nodeType==1?true:false;
   }catch(e){
       returnfalse;
   }
}
varobj1={nodeType:1};
varobj2=document.createTextNode("hello");
varobj2=document.createElement("p");
isHTMLElement(obj1);//false
isHTMLElement(obj2);//false
isHTMLElement(obj3);//true

对于window和document还要特别处理下
复制代码代码如下:
functionisHtmlControl(obj){ 

   vard=document.createElement("div");
   try{
       d.appendChild(obj.cloneNode(true));
       returnobj.nodeType==1?true:false;
   }catch(e){
       returnobj==window||obj==document;
   }