In this tutorial you will learn the concept of Document Object Model, or DOM.
Understanding the Document Object Model
The Document Object Model, or DOM for short, is a platform and language independent model to represent the HTML or XML documents. It defines the logical structure of the documents and the way in which they can be accessed and manipulated by an application program.
In the DOM, all parts of the document, such as elements, attributes, text, etc. are organized in a hierarchical tree-like structure; similar to a family tree in real life that consists of parents and children. In DOM terminology these individual parts of the document are known as nodes.
The Document Object Model that represents HTML document is referred to as HTML DOM. Similarly, the DOM that represents the XML document is referred to as XML DOM.
To understand this more clearly, let's consider the following simple HTML document:
ExampleTry this code »
<!DOCTYPE html> <html> <head> <title>My Page</title> </head> <body> <h1>Mobile OS</h1> <ul> <li>Android</li> <li>iOS</li> </ul> </body> </html>
The above HTML document can be represented by the following DOM tree:
The above diagram demonstrates the parent/child relationships between the nodes. The topmost node i.e. the Document node is the root node of the DOM tree, which has one child, the
<html> element. Whereas, the
<body> elements are the child nodes of the
<html> parent node.
<body> elements are also siblings since they are at the same level. Further, the text content inside an element is a child node of the parent element. So, for example, "Mobile OS" is considered as a child node of the
<h1> that contains it, and so on.
Comments inside the HTML document are nodes in the DOM tree as well, even though it doesn't affect the visual representation of the document in any way. Comments are useful for documenting the code, however, you will rarely need to retrieve and manipulate them.
HTML attributes such as
style, etc. are also considered as nodes in DOM hierarchy but they don't participate in parent/child relationships like the other nodes do. They are accessed as properties of the element node that contains them.
style property of the DOM elements can be used to get or set the inline style of an element.