Home >Web Front-end >JS Tutorial >How to determine whether an element is an HTMLElement element_javascript tips

How to determine whether an element is an HTMLElement element_javascript tips

WBOY
WBOYOriginal
2016-05-16 17:10:162325browse

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. 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_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_FRAGMENT_NODE = 11;
const unsigned short NOTATION_NODE = 12;

But what if our custom object also contains the nodeType attribute? For example,



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.


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


Special treatment is required for window and document




Copy code


The code is as follows: return obj.nodeType= =1 ? true : false;
}catch(e){
} return obj==window || obj==document;
}
}


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn