Javascript DOM Introduction

The Document Object Model (DOM) is an application programming interface (API) for HTML and XML documents.

The DOM represents a document as a hierarchical tree of nodes, allowing developers to add, remove, and modify individual parts of the page.

DOM is now a truly cross-platform, language-independent way of representing and manipulating pages for markup.

DOM Tree

Any HTML document can be represented as a hierarchy of nodes using the DOM.

There are several node types, each representing different information and/or markup in the document.

For instance, consider the following HTML:

        <title>Sample Page</title>

        <p>Hello World!</p>

The DOM tree for the code above.

 +--Element html
     +--Element head
     |   |
     |   +--Element title
     |       |
     |       +--Text Sample Page
     +--Element body
         +--Element p
             +--Text Hello World!

A document node represents every document as the root. The document element is the outermost element in the document. There can be only one document element per document.

In HTML pages, the document element is always the html element.

DOM Node Type

Every piece of markup can be represented by a node in the tree:

  • HTML elements are represented by element nodes
  • Attributes are represented by attribute nodes
  • Document type is represented by a document type node
  • Comments are represented by comment nodes

In total, there are 12 node types, all of which inherit from a base type.

DOM Level 1 has an interface called Node implemented by all node types in the DOM.

The Node interface is implemented in JavaScript as the Node type.

All node types inherit from Node in JavaScript, so all node types share the same basic properties and methods.

Every node has a nodeType property that indicates the type of node that it is. Node types are represented by one of the following 12 numeric constants on the Node type:


Node Type

A node's type is easy to determine by comparing against one of these constants:

  <pre id="results"></pre> 
    var resultsElement = document.getElementById("results"); 
    if (resultsElement.nodeType == Node.ELEMENT_NODE){ 
       //won't work in IE < 9
       document.writeln("Node is an element."); 
    } <!--from   w  ww  . j  ava 2 s .  c o m-->
    if (resultsElement.nodeType == 1){//works for all
       document.writeln("Node is an element."); 

Click to view the demo