The Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document. HTML DOM is a standard object model and programming interface for HTML. Simply put, the HTML DOM is a standard for how to get, change, add, or delete HTML elements.
DOM treats everything in an HTML document as a node. For example, the entire document is one document node, the elements within the document are element nodes, and text within those elements is text node. For example, consider the code:
1 2 3 4 5 6 7 8 9 |
<html> <head> <title>DOM Tutorial</title> </head> <body> <h1>DOM Lesson one</h1> <p>Hello world!</p> </body> </html> |
– The root node in the HTML above is <html>. All other nodes in the document are contained within <html>.
– The <html> node has two child nodes; <head> and <body>.
– The <head> node holds a <title> node. The <body> node holds a <h1> and <p> node.
So DOM treats an HTML document as a node hierarchy or a node tree in which there are parent-children relations between outer and inner nodes.
For the modification of the content of an HTML element, DOM uses the innerHTML property. The innerHTML property is useful for returning or replacing the content of HTML elements (including <html> and <body>). Consider the code:
1 2 3 4 5 6 7 8 9 |
<html> <body> <p id="intro">Hello World!</p> <script type="text/javascript"> txt=document.getElementById("intro").innerHTML; document.write("<p>The text from the intro paragraph: " + txt + "</p>"); </script> </body> </html> |
In the above code, getElementById is a method to specific a particular element, while innerHTML is a property used for modification of the content. Alternatively, same modification can be performed through the use of childNodes and nodeValue properties. For example:
1 2 3 4 5 6 7 8 9 |
<html> <body> <p id="intro">Hello World!</p> <script type="text/javascript"> txt=document.getElementById("intro").childNodes[0].nodeValue; document.write("<p>The text from the paragraph: " + txt + "</p>"); </script> </body> </html> |
In this code, getElementById is a method, while childNodes and nodeValue are properties. The facility afforded by DOM is that the manipulation of individual elements within a large HTML document is made easy for the web programmer.