In this article we will study about DOM, what are its characteristics and properties and in addition, we will see practical examples of how to use the DOM in JavaScript. The Document Object Model or simply DOM is used by web browser to represent your Web page . When this pattern is altered by the use of Javascript it also alters the Web page. It is much easier to use DOM directly with HTML or CSS.
Largely responsible for all this is the object “document” which is responsible for granting the Javascript code access to the entire DOM tree of the web browser. Hence anything created by the Web browser on the model of the web page can be accessed through the Javascript “document” object.
DOM is mainly used to update a Web page (DOM is widely used with Ajax) or when you want to build an advanced user interface. With DOM you can move items within a page or create very interesting CSS effects without even reloading the page.
Document object
Through the document object you can have access to a large number of properties. Below are some of the properties that can be used with the document object:
Property | Description |
documentElement | Capture root element of an HTML document. |
getElementById | Search an element of the Web page using the id attribute of the element. |
createElement | Creates a node element on the page. |
createAttribute | Creates an attribute node on the page. |
createTextNode | Creates a text node page. |
getElementsByTagName | Returns an array of elements with the same name. |
appendChild | Inserts a new child element. |
removeChild | Removes a child element. |
parentNode | Returns the parent node of a node. |
Below is an example of a DOM tree of a Web page:
Figure 1 . Example of a DOM tree from a Web page
- All web pages are somehow a tree. This is because we can see a Web page as a tree with a root as the HTML element and its children as the HEAD and BODY which in turn have child elements and so on.
- The elements that have no children are called leaf nodes, such as the elements TITLE, STYLE, SCRIPT, LI, H1, P, TD .
- Note that Text is a text that is inside an element. The nodeis also considered a node, but a node of a different type (type text).<
This tree structure is the way how a browser organizes the HTML markup. This is how the Web browser sees an HTML document. Reading Tree always occurs from left to right. A good practice to prevent browsers prevent the webpage in different ways is always to write standard HTML if possible always validate HTML page and close the elements correctly. The Document Object Model specifications are published by the World Wide Web Consortium (W3C). Therefore, the DOM is a de-facto standard.
Traversing DOM Trees
As seen in the above tree, we can go through it using the “document” in the Javascript code . As each node has a parent, and most have a child node, you can cover that trees DOM ascending and descending on it using these connections. Recalling that each node in a DOM tree includes texts, elements, attributes and also comments. All of them are grouped into an object by DOM Node. Elements and texts are special type nodes. When we have a node we can capture its name with nodeName and we can capture its nodeValue with its value. However, one must be careful because they can return a null value, for example, in the case of accessing an element node div that has a name but has no value. A text node in turn has a value but does not have a name.
It is important to differentiate between what is a text node and element node. For example, it takes the HTML below:
Example Listing 1 : Traversing trees
<html> <head> <title> Test DOM Tree</title> </head> <body> <p> you know about DOM trees? If not learn it at <a href="www.javabeat.net"> www.javabeat.net </ a> </ p> </body> </html>
This example has element nodes “p” and “a”. Its nodeName be “p” and “a” respectively. These nodes would like Element nodeValue null / undefined. The elements of the text would have for eg “you know about DOM trees? If not learn it at. ” In the example above there are also other elements of text as the child of “a”.
To know what type of node we are dealing we can use the property node nodeType that returns a number and that number is mapped to a value stored in the Node class. There is a value for each node type.
For example, to check if a node is of type Element or type text could be using Java script below:
Example Listing 2 : Checking the node type
if (someNode.nodeType == Node.ELEMENT_NODE) { / /Code here Else {} if (someNode .nodeType == Node.TEXT_NODE) { / / Code here } }
Be careful with this code, because some browsers may not support the Node. However, it has to know that the constant is 1 and the element 3 is constant in the text.
Let’s play a little with the access nodes and text nodes Elements printing its values and names as well as access their children.
Example Listing 3 : Printing values
<html> <head> <script language="javascript"> function testingDOMTree() { var element = document.documentElement.lastChild; alert ("I am the node " + element.nodeName); var anotherElement = document.getElementsByTagName('h1')[0]; alert ("I am the node " + anotherElement.nodeValue); var child = anotherElement.firstChild; alert ("I am the node " + child.nodeValue); } </script> <title> Test DOM Tree </title> </head> <body> <h1> Test Title </h1> <p> you know about DOM trees? If not learn it at <a href="www.javabeat.net"> www.javabeat.net </ a> </p> <span onclick="testingDOMTree();"> Click here to access the DOM Tree </ span> </body> </html>
Click on the text Click here to access the DOM Tree and see the execution of this example. Note that when we try to access the nodeValue of the h1 element that is a node of type Element you will see a null on the screen. This is due to the fact that h1 does not have a value for this property. Its child in the tree is a node that has a text value that is printed on the screen. The first command JavaScript “document.documentElement.lastChild” searches the last child node of . The first and the last is the and respectively.
Some more Examples
Below we will see some more examples of using DOM. The example below will display a notification in the user’s browser after five seconds.
Example Listing 4 : Sending notification to the user’s browser
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"/> <title> Notifier </title> <script> function notify (text) { document.getElementById('msg').innerHTML+='<p>'+text+'</p>'; titleFlick(); } function titleFlick(){ if(document.hasFocus()){ document.title = 'Notifier'; return; } document.title=document.title=='Notifier'?'* Notifier':'Notifier'; setTimeout('titleFlick()',500); } </script> </head> <body> <input type="button" id="notify" value="Notify in 5 seconds" onclick="notify('Will notify in 5 seconds...');setTimeout('notify(\'Event shoot!\')',5000)" /> <div id="msg"> </div> </body> </html>
If you want to create a sample tables zebradas using DOM, you can easily do using the code below.
Example Listing 5 : Creating table with DOM autoclave
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title> Zebra </title> <style> .zebraon {background: silver} </style> <script> window.onload = function () { var zebrar=document.querySelectorAll('.zebra tbody tr') for(var i=0;i<zebrar.length;i+=2) zebrar[i].className='zebraon' } </script> </head> <body> <table class="zebra"> <thead> <tr> <th> Seller </th> <th> Total </th> </tr> </thead> <tbody> <tr> <td> seller1 </td> <td> 12,300.00 </td></tr> <tr><td> seller2 </td> <td> 21,300.00 </td></tr> <tr><td> seller3 </td> <td> 13,200.00 </td></tr> <tr><td> seller4 </td> <td> 32100.00 </td></tr> <tr><td> seller5 </td> <td> 23100.00 </td></tr> <tr><td> seller6 </td> <td> 31200.00 </td></tr> </tbody> </table> </body> </html>
Summary
In this article we saw what the DOM is, why DOM is used by browsers and how it is used. We also saw how the browser sees an HTML document creating the DOM tree by organizing the HTML tags and how we can navigate through this tree. One can see the importance of understanding this important element that is often used to create complex and dynamic pages for the Web. Using the DOM your pages will be more rich, dynamic and intelligent.