Posted in Javascript onDecember 06, 2013
我们经常使用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属性呢?如
var obj = {nodeType:1}; function isHTMLElement(obj){ if(obj.nodeType){ return obj.nodeType==1; } } isHTMLElement(obj);//true
以上isHTMLElement(obj)返回true,但obj明显不是一个HTML节点元素。下面通过对象特性及try-catch语句来判断。
function isHTMLElement(obj){ var d = document.createElement("div"); try{ d.appendChild(obj.cloneNode(true)); return obj.nodeType==1?true:false; }catch(e){ return false; } } var obj1 = {nodeType:1}; var obj2 = document.createTextNode("hello"); var obj2 = document.createElement("p"); isHTMLElement(obj1);//false isHTMLElement(obj2);//false isHTMLElement(obj3);//true
对于window和document还要特别处理下
function isHtmlControl(obj) { var d = document.createElement("div"); try{ d.appendChild(obj.cloneNode(true)); return obj.nodeType==1 ? true : false; }catch(e){ return obj==window || obj==document; } }
如何判断元素是否为HTMLElement元素
声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@