DOM Tree and Nodes

By Srijan 15 June, 2018
Introduction to DOM
Photo by Clint Adair on Unsplash

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.

DOM Nodes

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

  1. document node
  2. element node
  3. text node
  4. comment node

Document Node

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.

Introduction to DOM

Top level nodes in a document (html, head, body) can be directly accessed using properties of document node:

  1. document.documentElement - <html>
  2. document.head - <head>
  3. document.body - <body>

We used Node.tagName property in above example which returned the name of selected node.

Element 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:

Value Constant
1 Node.ELEMENT_NODE
9 Node.DOCUMENT_NODE
3 Node.TEXT_NODE
8 Node.COMMENT_NODE

As shown in above example, Node.nodeType returned "1" for h1 element showing that h1 is of type element node.

Text Node

Introduction to DOM

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:

Property Description
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.

Comment Node

HTML comments are represented by comment node in a DOM tree. Comment node can also be accessed using javascript.



In next article we will discuss different types of relationship between DOM nodes.

Recommended Reading

Useful Resources



Follow us on
Sponsored