Working with the core DOM

HTML documents have a hierarchical structure which is represented in the DOM (Document Object Module) as a tree structure. Each tree node (which is an HTML element, text, comment, attribute, etc.) excluding the Document node has a unique parent node, which is located above in the diagram, and might have several child nodes. The nodes having the same parent node are called siblings.

The Node interface of the Window object defines several constants, attributes and methods for manipulating the tree nodes. Different types of nodes are represented by various subinterfaces of the Node interface (there are totally 12 subinterfaces), some of them are listed in the table. More information can be found at the W3C web site.

Interface nodeType const nodeType value
Element Node.ELEMENT_NODE 1
Attr Node.ATTRIBUTE_NODE 2
Text Node.TEXT_NODE 3
Entity Node.ENTITY_NODE 6
Comment Node.COMMENT_NODE 8
Document Node.DOCUMENT_NODE 9

Here are some attributes of the Node interface, each of them is read only:

Value type Attribute
DOMString nodeName
unsigned short nodeType
Node parentNode
NodeList childNodes
Node firstChild
Node lastChild
Node previousSibling
Node nextSibling

NodeList is a list (array) of node references, which can be accessed by index. If an object does not exist (e.g., nextSibling), the corresponding value is null. The Node interface also defines several methods:

Return value Method
Node insertBefore(Node newChild, Node refChild) raises(DOMException);
Node replaceChild(Node newChild, Node oldChild) raises(DOMException);
Node removeChild(Node oldChild) raises(DOMException);
Node appendChild(Node newChild) raises(DOMException);
boolean hasChildNodes();
Node cloneNode(boolean deep);

Check the W3C document for a detailed description of these documents and methods. Here is an example of using these methods for computing the number of tags in a document.

function countTags(n)
{
  var tagsCount = 0;
  if (n.nodeType == Node.ELEMENT_NODE)
    tagsCount++;
  var kids = n.childNodes;
  for (var i=0; i<kids.length; i++)
    tagsCount += countTags(kids[i]);
  return(tagsCount);
}

Check how it works: