Node.nodeType

Node.nodeType 唯讀屬性表示了節點物件的類型。

描述

The nodeType property can be used to distinguish different kind of nodes, such that elements, text (en-US) and comments (en-US), from each other.

語法

var type = node.nodeType;

Returns an integer value which specifies the type of the node; possible values are listed in Node type constants.

常數

節點類型常數

Constant Value Description
Node.ELEMENT_NODE Read only 1 表示元素的 Element 節點,如 <body> (en-US)<a><p> (en-US)<script><style> (en-US)<html> (en-US)<h1> (en-US)<div>
Node.ATTRIBUTE_NODE 2 An Attribute (en-US) of an Element.
Node.TEXT_NODE Read only 3 於表示元素的 Element 節點或表示 HTML 元素屬性Attr (en-US) 節點中,表示了實際文字字元的 Text (en-US) 節點,它包括了換行與空格。
Node.CDATA_SECTION_NODE 4 A CDATASection (en-US).
Node.PROCESSING_INSTRUCTION_NODE Read only 7 A ProcessingInstruction (en-US) of an XML document such as <?xml-stylesheet ... ?> declaration.
Node.COMMENT_NODE Read only 8 表示註解的 Comment (en-US) 節點。
Node.DOCUMENT_NODE Read only 9 表示文件的 Document 節點。
Node.DOCUMENT_TYPE_NODE Read only 10 表示文件類型的 DocumentType 節點,例如 HTML5 的 <!DOCTYPE html>
Node.DOCUMENT_FRAGMENT_NODE Read only 11 A DocumentFragment node.

The following constants have been deprecated and are not in use anymore: Node.ENTITY_REFERENCE_NODE (5), Node.ENTITY_NODE (6), and Node.NOTATION_NODE (12).

範例

Different types of nodes

document.nodeType === Node.DOCUMENT_NODE; // true
document.doctype.nodeType === Node.DOCUMENT_TYPE_NODE; // true

var fragment = document.createDocumentFragment();
fragment.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 node, and if it is not, displays a message.

var node = document.documentElement.firstChild;
if (node.nodeType != Node.COMMENT_NODE)
  console.log("You should comment your code well!");

規範

Specification
DOM Standard
# ref-for-dom-node-nodetype①