SoFunction
Updated on 2025-04-07

How to determine whether an element is an HTMLElement element

We often use nodeType==1 to determine whether an element is an HMTLElement element. The elements on the page are nodes (Nodes), including element nodes (Element Nodes), attribute nodes (Attribute Nodes), text nodes (Text Nodes), etc. The definition of w3c nodeType is 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 the object we customize also contains the nodeType attribute? like

Copy the codeThe code is as follows:

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

The above isHTMLElement(obj) returns true, but obj is obviously not an HTML node element. The following is to judge by object characteristics and try-catch statement.
Copy the codeThe code is as follows:

function isHTMLElement(obj){
    var d = ("div");
    try{
        ((true));
        return ==1?true:false;
    }catch(e){
        return false;
    }
}
var obj1 = {nodeType:1};
var obj2 = ("hello");
var obj2 = ("p");
isHTMLElement(obj1);//false
isHTMLElement(obj2);//false
isHTMLElement(obj3);//true

Special handling of window and document
Copy the codeThe code is as follows:

function isHtmlControl(obj) { 

    var d = ("div");
    try{
        ((true));
        return ==1 ? true : false;
    }catch(e){
        return obj==window || obj==document;
    }