JS HTML DOM



The Document Object Model ( DOM ), is representation of the elements of the HTML through which JavaScript can interacts with content within a website. Using the DOM approach it is possible to access, traverse and manipulate HTML and XML documents.

To stay away from the technical terms and focus instead on the practical example, let us try to add some text on an existing html page on click of a button. Consider the following example



  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <script>
  5. /*
  6. ************************************
  7. ReferenceDesigner.com DOM Tutorial
  8. ************************************
  9. */
  10.  
  11. function addText()
  12. {
  13. document.getElementById("addtxt").innerHTML="DOM Tutorial by ReferenceDesigner.com";
  14. }
  15. </script>
  16. </head>
  17. <body>
  18.  
  19. <p>Click the button and it will add some text.</p>
  20. <button onclick="addText()">Hit me</button>
  21. <p id="addtxt"></p>
  22.  
  23. </body>
  24. </html>




This exmaple will add text on the paragraph with id addtxt on clicking the button.
You may like to try this example here.

Explanation


The GetElementById method is used to refer to an HTML element with an given unique id for processing. It returns a reference to an object that represents an element on the page, in the case of an HTML document. The element can then be examined or manipulated through this object.

The innerHTML property sets or returns the inner HTML of an element.

We will look into the details of the innerHTML property later on. For the moment, try out the following exercises.

Exercise 1


Change this example so that on clicking the button, the text which is cuurently displayed as

DOM Tutorial by ReferenceDesigner.com

is now displayed with ReferenceDesigner.com in bold.