All objects in a document tree (including the Document object itself) implement the Node interface, which provides the fundamental properties and methods for traversing and manipulating the tree. The parentNode property and childNodes[] array allow you to move up and down the document tree. You can enumerate the children of a given node by looping through the elements of childNodes[] or by using the firstChild and nextSibling properties (or the lastChild and previousSibling properties, to loop backward). The appendChild(), insertBefore(), removeChild(), and replaceChild() methods allow you to modify the document tree by altering the children of a node.

Every object in a document tree implements both the Node interface and a more specialized subinterface, such as Element or Text. The nodeType property specifies which subinterface a node implements. You can use this property to test the type of a node before using properties or methods of the more specialized interface. For example:

var n;   // Holds the node we're working with
if (n.nodeType == 1) {       // Or use the constant Node.ELEMENT_NODE
    var tagname = n.tagName; // If the node is an Element, this is the tag name


unsigned short ELEMENT_NODE = 1unsigned short TEXT_NODE = 3unsigned short PROCESSING_INSTRUCTION_NODE = 7unsigned short COMMENT_NODE = 8unsigned short DOCUMENT_NODE = 9unsigned short DOCUMENT_TYPE_NODE = 10unsigned short DOCUMENT_FRAGMENT_NODE = 11

These constants are possible values of the nodeType ...

Get JavaScript: The Definitive Guide, 6th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.