We often use nodeType==1 to determine whether an element is an HMTLElement element. 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 the nodeType attribute? like
Copy the code code as follows:
var obj = {nodeType:1};
function isHTMLElement(obj){
if(obj.nodeType){
return obj.nodeType==1;
}
}
isHTMLElement(obj);//true
The above isHTMLElement(obj) returns true, but obj is obviously not an HTML node element. The following is judged by object characteristics and try-catch statements.
Copy the code code as follows:
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
Special treatment is required for window and document.
Copy the code code as follows:
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;
}
}