HTML DOM Introduction

The DOM or Document Object Model is a standard object model for HTML. It defines the objects and properties of all document elements, and the methods (interface) to access them. DOM allows programs and scripts to dynamically access and update the content, structure and style of HTML documents by associating them with an object oriented mode. In simple words the HTML DOM is a standard for how to get, change, add, or delete HTML elements.

When a web page is loaded, the browser creates a Document Object Model of the page. The HTML DOM model is constructed as a tree of Objects. For example consider the below html document :
<html>
<head>
  <title>My title</title>
  <meta charset="UTF-8">
</head>
<body>
  <h1>My heading</h1>
  <p>This is paragraph</p>
  <table>
    <tr>
      <td>Some table content</td>
    </tr>
  </table>
</body>
</html>

The Document Object Model representation of the above html document is like this:


With the object model, JavaScript gets all the power it needs to create dynamic HTML. In the DOM, everything in an HTML document is a node. For example the entire document is a document node, every HTML element is an element node, the text in the HTML elements are text nodes and every HTML attribute is an attribute node. 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.

Now lets see a simple example of HTML DOM :
<html>
<head>
  <script>
    function printFunc() {
      var text = document.getElementById('box').value;
      document.getElementById('demo').innerText = "Hello " + text;
    }
  </script>    
</head>
<body>
  <p>Enter your Name :</p>
  <input type="text" id="box"/>
  <input type="button" onclick="printFunc()" value="Click Here"/>
  <p id="demo"></p>
</body>
</html>
Output :


Enter your Name :



At the above example, when the user click the button then the text in the textbox wiil printed out. As we can see that the document is the root element that represents the whole html document. Which grabs the textbox text by using getElementById() method where the value property returns the input text and then set the value of the empty paragraph by using innerText property.

Next Topic :