JavaScript and Dynamic Documents

Document Object Model, Manipulating the DOM with JavaScript

HTML Document Object Model (DOM)

"On a Web page, the objects that make up the page (or document) are represented in a tree structure. You've seen this sort of thing before when building HTML pages; the top level of the page is contained in the <html> tag, and inside that you'll find the <head> and <body> tags, with other tags within each of those, and so on. Some browsers can show you representations of this tree structure.... Java Script considers each of these items in the document tree to be objects and you can use JavaScript to manipulate those objects. The representation of the objects within the document is called the Document Object Model (DOM)." (JavaScript and Ajax, Sixth Edition by Tom Negrino and Dori Smith)

Representing an HTML Document by a DOM Tree

Here's the source code of an HTML page, in this simple example we don't have the HTML <head>

<html>
	<body>
		<p id="ptag1">The first <b>P tag</b></p>
		<p id="ptag2">The second P tag</p>
		<p align="left">The third <b id="btag1">P tag</b></p>
	</body>
</html>

The corresponding DOM TREE looks like this:


            The HTML Document Tree:
               

            <html>
               |
               |--------------------------------------other nodes (<HEAD>)
               |
            <BODY>
               |
               |----------------------------------------
               |                     |                  |
        <P id="ptag1">         <P id="ptag2">          <P>
               |                     |                  |
         --------------              |             --------------
        |              |        The second P tag  |              |
    The first         <B>                    The third      <B id="btag1">
                       |                                         |
                       |                                         |
                     P tag                                     P tag

Now, with Level 1 DOM (and up) , you often see things accessed using an id. If you had assigned an id to the input box, as in
<input type="text" name="age" id="age_id" />, you could also access the value with the following syntax:
document.getElementById("age_id").value

JS HTML DOM: http://www.w3schools.com/js/js_htmldom.asp

Manipulating HTML DOM with JavaScript

You can change your HTML page by manipulating the DOM of the HTML. First, you need to find the HTML element to make a change. After that, you can change the content of the element, i.e., the value of a text node or other html elements. For example, you can add a P tag into the end of an HTML <body> or delete a link <a> in a paragraph P. In other words: The HTML DOM is a standard for how to get,change,add,or delete HTML elements (w3schools.com).

Typical DOM Operations:

The Following JavaScript Statements demonstrate typical HTML DOM operations based on the example in the early section.

  • Access a node (HTML elements, e.g., a P tag):
    1. Find the first P tag:
      var ptag1 = document.getElementById("ptag1");
      var ptag1 = document.firstChild.firstChild;
      
    2. Find the second P tag:
      var ptag2 = document.getElementsByTagName('P')[1];
      
    3. Find the third P tag:
      var ptag3 = document.firstChild.lastChild;
      var ptag3 = document.getElementById("btag1").parentNode;
      var ptag3 = document.firstChild.childNodes[2];
      
  • Access a text node (the text or content) of the second P tag, and then change the value:
    // find the second <p> tag: 
    var ptag2 = document.getElementById("ptag2");
    
    // find the text node of it: 
    var txt2 = ptag2.firstChild;
    
    // change the value of the text node: 
    txt2.nodeValue = "we changed the text of the second P tag";
    			
  • Access an attribute of an HTML element:
    // set the inline style sheet of the third P tag: 
    var ptag3 = document.firstChild.childNodes[2];
    ptag3.setAttribute('style','color:red');
    
    // You can also add other attributes to the external css p tag:
    ptag3.setAttribute('class','a_css_class_name');
    
  • Create a node (i.e., an HTML element):
    /*
     * Following two statements will create a P tag 
     * with the text "This is the fourth p tag".
     */
    
    // create a P tag: 
    var new_ptag4 = document.createElement('p');
    
    // create a text node (content of the P tag): 
    var new_txt4 = document.createTextNode('This is the fourth p tag');
    
    /*
     * Note: We didn't attach or insert the text node 
     * into the fourth P tag yet. The newly created 
     * P is not attached or inserted to any HTML element 
     * either. That is, you are not able to see the newly created 
     * P tag with a content "This is the fourth p tag" in 
     * your HTML page.
     */
    
  • Insert a node into the end of another node:
    /* 
     * Now we will add the fourth P tag into the 
     * end of the HTML Body tag.
     */
    
    var node_body = document.firstChild;
    
    // adding the fourth p tag at the end of HTML body:
    node_body.appendChild(new_ptag4);
       
    // adding a text node (text information) to the fourth P tag:
    new_ptag4.appendChild(new_txt4);
    
  • Remove a node from the parent node:
       var ptag3 = document.firstChild.childNodes[2];
       var node_to_delete   = document.getElementById("btag1");
       ptag3.removeChild(node_to_delete);
    

JS HTML DOM Methods: http://www.w3schools.com/js/js_htmldom_methods.asp

An Alternative Approach by Using innerHTML

You can also use an attribute .innerHTML to change the content of an HTML element.

HTML innerHTML: http://www.w3schools.com/jsref/prop_html_innerhtml.asp

Important Notes

JavaScript code is run on a browser only (client-side). Sometimes, certain parts of JavaScript are not supported in a specific version of a browser. Rather than checking for the browser that you are using, you can check to see if certain objects are supported. This is known as object detection versus browser detection.

JavaScript Regular Expression Form Validation

A online form usually asks for information related to name, phone no, address, credit-card no etc. If you didn't provide information in the format specified by the form field or leave it empty, the message will appear and form cannot be submitted until you get it right. This is done using a Javascript program on the client side, the Javascript program uses a regular expression pattern to test the input of each form field.

Here are a few useful links on how to use regular expression.

Regular Expression Cheat Sheet
http://emailregex.com/regular-expressions-cheat-sheet/http://emailregex.com/regular-expressions-cheat-sheet/
http://www.tutorialspark.com/javascript/JavaScript_Regular_Expression_Form_Validation.php
https://www.formget.com/form-validation-using-javascript/
http://stackoverflow.com/questions/940577/javascript-regular-expression-email-validation
http://www.9lessons.info/2009/03/perfect-javascript-form-validation.html
JavaScript test() Method
JavaScript exec() Method

In Class Exercise Lab Assignment

Details:

Create a form SignUp_dom.html

you will use external JavaScript SignUp.js to display all of the proper input.

When the SignUp button is clicked, a JavaScript will be called to validate the format of each field.

Red text will appear above the field(s) if invalid format or empty fields.

You can use innerHTML or DOM Operations for this. The following is an example of the invalid input in red text.

Note:

Make sure to design a proper logic. If some fields have valid input, only the invalid input message should be displayed.

If all input is valid, the detailed user information should be displayed.


Link your SignUp_dom.html on the index.html and name the link Lab 5 DOM.

Zip SignUp_dom.html and your SignUp.js files, upload in URcourses by 11:55PM.