In last article - Introduction to DOM we saw how DOM tree is constructed by the browser for further processing of the web page. In this article, we will discuss some common node types that are present in almost all HTML documents and also look into their associated properties.
A tree is constructed from nodes. There are 12 node types available as per w3c standards for construction of DOM Tree (in latest specification DOM4, five node types have been deprecated, i.e. marked for removal from future versions). DOM nodes are implemented as objects with their own properties and methods. Four frequently used node types that are present in almost all HTML documents are
Document Node is the root of DOM Tree and represents the entire document that is loaded into the browser. It is entry point to the document. We can access any other node in the DOM tree from document node.
Top level nodes in a document (html, head, body) can be directly accessed using properties of document node:
We used Node.tagName property in above example which returned the name of selected node.
HTML tags become element nodes in DOM tree. We can get node type by using Node.nodeType property. Node.nodeType returns a numeric value corresponding to type of node. Below table shows numeric value and node type they represent:
As shown in above example, Node.nodeType returned "1" for h1 element showing that h1 is of type element node.
A text node is always leaf of the DOM tree. An HTML element consists of an element node and a text node in general. In above example, we used following new properties:
|Node.nodeName||Returns name of the current node as a string. For a text node it will return "#text".|
|Node.nodeValue||Returns or sets value of the current node. For text node and comment node it will return the content. For document and element node it will return null.|
|Node.childNodes||Returns a live NodeList of child nodes of the given element. Particular Child can be selected by specifying an index which starts at '0' for the first element. Nodelist is a collection of nodes and "live" here means that NodeList will reflect any changes in DOM instantly.|
In next article we will discuss different types of relationship between DOM nodes.