Document Object Model or DOM is a programming interface for the document (HTML, Dynamic HTML or XML) which provide the ability to manipulate the elements (HTML tags and String literal) that makes up a document.
In a normal scenario, when server sends the response in the form of an HTML page, browser takes that HTML page and keeps it in memory. The responsibility of DOM is to create a hierarchy structure of HTML elements from the HTML page stored in browser’s memory.
Structure of DOM
HTML document have a hierarchical structure in which document objects are represented as a TREE. Each node of Tree represents an HTML document (tags, string text). Let us look at a small example:
Here is a small HTML page (document)
<html> <head> <title>This is test document</title> </head> <body> <p id="p1">First sentence</p> <p id="p2">Second sentence</p> </body> </html>
Representing the above HTML document in the form of DOM Tree
Each of these nodes represents a Node object. Node object has some methods and properties to traverse these nodes in HTML document. Some of these properties are nextChild, previousChild, nextSibling, previousSibling.
Accessing Node Object
Node elements can be accessed by document object. In the next example we will see how to access the node element and traverse the parent and the child node elements.
Finding out different HTML elements (Nodes)
Find out how many Head nodes we have in out HTML document
and the answer is
Similarly, let’s find out how many paragraph elements we have in out HTML document
and number of paragraph elements are:
Traversing DOM Nodes
In this section we will see how to traverse through Parent and Child nodes and Siblings as well. We have 2 paragraph elements in this HTML document. Let us try accessing the first paragraph element and then traverse to its sibling element.
The above alert statement will give the following output
Now traversing to the Next Sibling of first paragraph element
and this time alert will give the following output
Similarly, we can access previousSibling, previousElementSibling to access the previous sibling nodes.