How to determine whether elements are htmlelement elements _javascript skills

Source: Internet
Author: User

We often use nodetype==1 to determine whether an element is a hmtlelement element. The elements on the page are nodes, element nodes, attribute nodes, text nodes, and so on, and so on. The definition of the NodeType of the consortium 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 our custom object also contains the NodeType attribute? Such as

Copy 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 are judged by object characteristics and Try-catch statements.
Copy 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

The window and document should be handled in particular
Copy 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;
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.