判断元素是否为HTMLElement元素

我们经常使用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;
	}
}	

posted on 2011-03-12 07:11  snandy  阅读(7050)  评论(4编辑  收藏  举报