W3cubDocs

/DOM

Node.nodeType

The read-only Node.nodeType property that represents the type of the node.

Description

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

Syntax

var type = node.nodeType;

Returns an integer value 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 such as <p> or <div>.
Node.TEXT_NODE 3 The actual Text of Element or Attr.
Node.CDATA_SECTION_NODE 4 A CDATASection.
Node.PROCESSING_INSTRUCTION_NODE 7 A ProcessingInstruction of an XML document such as <?xml-stylesheet ... ?> declaration.
Node.COMMENT_NODE 8 A Comment node.
Node.DOCUMENT_NODE 9 A Document node.
Node.DOCUMENT_TYPE_NODE 10 A DocumentType node e.g. <!DOCTYPE html> for HTML5 documents.
Node.DOCUMENT_FRAGMENT_NODE 11 A DocumentFragment node.

Deprecated node type constants

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

Constant Value Description
Node.ATTRIBUTE_NODE 2 An Attribute of an Element. The element attributes are no longer implementing the Node interface 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.

Examples

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

Specifications

Browser compatibilityUpdate compatibility data on GitHub

Desktop
Chrome Edge Firefox Internet Explorer Opera Safari
Basic support Yes 12 ? ? Yes ?
Mobile
Android webview Chrome for Android Edge Mobile Firefox for Android Opera for Android iOS Safari Samsung Internet
Basic support Yes Yes ? ? Yes ? Yes

© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType