DOM in Java Script

Introduction to the Document Object Model

The Document Object Model, or DOM, is the interface that allows you to programmatically access and manipulate the contents of a web page (or document). It provides a structured, object-oriented representation of the individual elements and content in a page with methods for retrieving and setting the properties of those objects. It also provides methods for adding and removing such objects, allowing you to create dynamic content.

The DOM also provides an interface for dealing with events, allowing you to capture and respond to user or browser actions. This feature is briefly covered here but the details are saved for another article. For this one, the discussion will be on the DOM representation of a document and the methods it provides to access those objects.

The Document Tree

When a browser loads a page, it creates a hierarchical representation of its contents which closely resembles its HTML structure. This results in a tree-like organization of nodes, each representing an element, an attribute, content or some other object.

Nodes

Each of these different object types will have their own unique methods and properties. But each also implements the Node interface. This is a common set of methods and properties related to the document tree structure. To understand this interface better, take a look a the diagram below which represents a simple node tree.

The Node object provides several properties to reflect this structure and allow you to traverse the tree. Here are some relationships using the example above:

  • NodeA.firstChild = NodeA1
  • NodeA.lastChild = NodeA3
  • NodeA.childNodes.length = 3
  • NodeA.childNodes[0] = NodeA1
  • NodeA.childNodes[1] = NodeA2
  • NodeA.childNodes[2] = NodeA3
  • NodeA1.parentNode = NodeA
  • NodeA1.nextSibling = NodeA2
  • NodeA3.prevSibling = NodeA2
  • NodeA3.nextSibling = null
  • NodeA.lastChild.firstChild = NodeA3a
  • NodeA3b.parentNode.parentNode = NodeA

The Node interface also provides methods for dynamically adding, updating and removing nodes such as:

  • insertBefore()
  • replaceChild()
  • removeChild()
  • appendChild()
  • cloneNode()

These will be covered later. But for now let’s look how the document tree reflects the contents of a web page.

[in more details http://www.brainjar.com/dhtml/intro/%5D

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s