Node.nodeType - Web APIs 编辑
The read-only Node.nodeType
property is an integer that identifies what the node is. It distinguishes different kind of nodes from each other, such as elements
, text
and comments
.
Syntax
var type = node.nodeType;
Returns an integer which specifies the type of the node. Possible values are listed in Node type constants.
Constants
Node type constants
Constant | Value | Description |
---|---|---|
Node.ELEMENT_NODE | 1 | An Element node like <p> or <div> . |
Node.ATTRIBUTE_NODE | 2 | An Attribute of an Element . |
Node.TEXT_NODE | 3 | The actual Text inside an Element or Attr . |
Node.CDATA_SECTION_NODE | 4 | A CDATASection , such as <!CDATA[[ … ]]> . |
Node.PROCESSING_INSTRUCTION_NODE | 7 | A ProcessingInstruction of an XML document, such as <?xml-stylesheet … ?> . |
Node.COMMENT_NODE | 8 | A Comment node, such as <!-- … --> . |
Node.DOCUMENT_NODE | 9 | A Document node. |
Node.DOCUMENT_TYPE_NODE | 10 | A DocumentType node, such as <!DOCTYPE html> . |
Node.DOCUMENT_FRAGMENT_NODE | 11 | A DocumentFragment node. |
Deprecated node type constants This deprecated API should no longer be used, but will probably still work.
The following constants have been deprecated and should not be used anymore.
Constant | Value | Description |
Node.ENTITY_REFERENCE_NODE | 5 | An XML Entity Reference node, such as &foo; . Removed in DOM4. |
Node.ENTITY_NODE | 6 | An XML <!ENTITY …> node. Removed in DOM4. |
Node.NOTATION_NODE | 12 | An XML <!NOTATION …> node. Removed in DOM4. |
Examples
Different types of nodes
document.nodeType === Node.DOCUMENT_NODE; // true
document.doctype.nodeType === Node.DOCUMENT_TYPE_NODE; // true
document.createDocumentFragment().nodeType === Node.DOCUMENT_FRAGMENT_NODE; // true
var p = document.createElement("p");
p.textContent = "Once upon a time…";
p.nodeType === Node.ELEMENT_NODE; // true
p.firstChild.nodeType === Node.TEXT_NODE; // true
Comments
This example checks if the first node inside the document element is a comment, and displays a message if not.
var node = document.documentElement.firstChild;
if (node.nodeType !== Node.COMMENT_NODE) {
console.warn("You should comment your code!");
}
Specifications
Specification | Status | Comment |
---|---|---|
DOM The definition of 'Node.nodeType' in that specification. | Living Standard | Deprecated ATTRIBUTE_NODE , ENTITY_REFERENCE_NODE and NOTATION_NODE types. |
Document Object Model (DOM) Level 3 Core Specification The definition of 'Node.nodeType' in that specification. | Obsolete | No changes. |
Document Object Model (DOM) Level 2 Core Specification The definition of 'Node.nodeType' in that specification. | Obsolete | No changes. |
Document Object Model (DOM) Level 1 Specification The definition of 'Node.nodeType' in that specification. | Obsolete | Initial definition. |
Browser compatibility
BCD tables only load in the browser
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论