Document Object Model

A formal definition: The DOM is a cross platform, language independent, API for HTML, XHTML and XML documents that allows programs and scripts to dynamically access and change the style content and structure of a document.

 

Or: The DOM is a model (structure) of the objects (nodes) for a web page (the document) that provides a standard method of showing how a web page is made up, that can be used on any machine using any browser it chooses, allowing scripts to be able to manipulate how the page looks and behaves.

 

 

Browsers include a JavaScript engine (interpreter) that recognises standard instructions that allow access to the nodes (objects) of the webpage (document).

 

Whenever a web page is loaded by browser, its JavaScript engine creates a DOM of that page as a number of node objects.

 

Of the twelve node types, the three main nodes we're interested in are:

  • The ELEMENT node
    • html tags e.g. <body>, <h1>, <p>, <ul>, etc.
  • The ATTRIBUTE node
    • tag attributes within an elements < angled brackets> e.g. class="myClass", id="myId", style="myStyle", etc.
  • The TEXT node
    • This is the actual text content between the opening and closing tags e.g. <p>This is the text content node</p>

 

The DOM for a web page can easily become very large. Given a very simple html file:

 

The DOM can be depicted as follows:

¬†DOM nodes 

 

The above image represent all nodes for the above html, and can be broken down as follows:

  • The ELEMENT node
    • Node.ELEMENT_NODE == 1

Element node

  • The ATTRIBUTE node
    • Node.ATTRIBUTE_NODE == 2

Attribute node

  • The TEXT node
    • Node.TEXT_NODE == 3

Text node

 

The node types can be accessed by JavaScript using the .nodeType method. For example:

Save & refresh browser:

The body element returns a node type value of: 1

Leave a Reply