How do I tell if an element is a HTMLElement


We often use nodeType==1 to determine whether the element is a HMTLElement. The elements on the page are all nodes, including Element Node, Attribute Node, Text Node, etc. W3c nodeType is defined as follows

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;

But what if our custom object also contains a nodeType attribute? Such as

var obj = {nodeType:1};
function isHTMLElement(obj){
    if(obj.nodeType){
        return obj.nodeType==1;
    }
}
isHTMLElement(obj);//true

The isHTMLElement(obj) above returns true, but obj is clearly not an HTML node element. Let’s look at the object properties and the try-catch statement.

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

I’m going to do something special with Windows and documents

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;
    }