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.TEXT_NODE Read only 3 於表示元素的 Element 節點或表示 HTML 元素屬性Attr (en-US) 節點中,表示了實際文字字元的 Text (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.

已過時的節點類型常數  Deprecated

The following constants have been deprecated and should not be used anymore.

Constant Value Description
Node.ATTRIBUTE_NODE 2 An Attribute (en-US) of an Element. The element attributes are no longer implementing the Node interface in DOM4 specification.
Node.CDATA_SECTION_NODE 4 A CDATASection (en-US). Removed in DOM4 specification.
Node.ENTITY_REFERENCE_NODE 5 An XML Entity Reference node. Removed in DOM4 specification.
Node.ENTITY_NODE 6 An XML <!ENTITY ...> node. Removed in DOM4 specification.
Node.NOTATION_NODE 12 An XML <!NOTATION ...> node. Removed in DOM4 specification.


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


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!");