Understanding what a DOM Tree and Node is all about

A JavaScript Basic Concept

Understanding what a DOM Tree and Node is all about

What exactly is a DOM?

For starters, DOM is an acronym for Document Object Model. It is an object for the document that actually houses other objects. According to w3.org

the document object model is a programming API for HTML and XML documents. It defines the logical structure which is very much like a tree.

We can hence decipher that from our little knowledge of DOM, every HTML tag is an object, nested tags are “children” of the enclosing one, and the text inside a tag is an object also. Since we can agree to that extend we can equally and comfortable say the the JavaScript can access these objects and make changes to the document object model (DOM). Personally I feel the easiest way to access the DOM is through the id attribute

<!DOCTYPE html>
<html lang="en">

  <head>
    <title>Learning the DOM</title>
  </head>

  <body>
    <h1>Document Object Model</h1>
<a id="nav" href="index.html">Home</a>
</body>
  </body>

</html>

Using the getElementById() method we are going to access the entire element

document.getElementById('nav');

DOM Tree

Everything in the HTML has its place in the DOM tree. The DOM structure represent the HTML as a tree of objects of the documents. To understand DOM tree, we need to understand the what node is? According to Tania Racia

All items in the DOM are defined as nodes. There are many types of nodes, but there are three main ones that we work with most often:

  • Element nodes
  • Text nodes
  • Comment nodes When an HTML element is an item in the DOM, it is referred to as an element node. Any lone text outside of an element is a text node, and an HTML comment is a comment node. In addition to these three node types, the document itself is a document node, which is the root of all other nodes.

The DOM consists of a tree structure of nested nodes, which is often referred to as the DOM tree. You may be familiar with an ancestral family tree, which consists of parents, children, and siblings. The nodes in the DOM are also referred to as parents, children, and siblings, depending on their relation to other nodes. The DOM representation of the example table is shown below slide_2.jpg