1 / 43

Document Object Model

Document Object Model. OBJECTIVES. In this chapter you will learn: How to use JavaScript and the W3C Document Object Model to create dynamic web pages. The concept of DOM nodes and DOM trees. How to traverse, edit and modify elements in an XHTML document. Introduction.

Download Presentation

Document Object Model

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Document Object Model

  2. OBJECTIVES In this chapter you will learn: • How to use JavaScript and the W3C Document Object Model to create dynamic web pages. • The concept of DOM nodes and DOM trees. • How to traverse, edit and modify elements in an XHTML document.

  3. Introduction • The Document Object Model gives you access to all the elements on a web page. Using JavaScript, you can create, modify and remove elements in the page dynamically. • With the DOM, XHTML elements can be treated as objects, and many attributes of XHTML elements can be treated as properties of those objects. Then, objects can be scripted (through their id attributes) with JavaScript to achieve dynamic effects.

  4. DOM • The document object model is a representation of the whole document as nodes and attributes • You can access each of these nodes and attributes and change or remove them • You can also create new ones or add attributes to existing ones

  5. DOM <HTML> <BODY> <table border="0" cellspacing="2" cellpadding="5"> <tr> <td colspan="2"><imgsrc="Greetings.jpg“/></td> </tr> <tr> <td> Welcome to my sample HTML page! <br /> <a href="somelink.html" id="myLink" >Click Here!</a> </td> <td><imgsrc="hello.jpg" id="helloImg" /></td> </tr> </table> </BODY> </HTML>

  6. HTML DOM Element Node <html>  <head>    <title>DOM Tutorial</title>  </head>  <body>  </body></html> firstChild Text Node (Access using innerHTML property LastChild

  7. Document Object Methods

  8. Document : Open() and close() <html> <head> <script type="text/javascript"> function createDoc() { vardoc=document.open("text/html","replace"); doc.write("<html><body><h1>SelamatDatangKeDunia DOM dan” + “JavaScript</body></h1></html>"); doc.close(); } </script> </head> <body> <input type="button" value="New document" onclick="createDoc()" /> </body> </html> Example

  9. getElementById() <html> <head><script type="text/javascript"> function getValue()  {var x=document.getElementById("myHeader");   alert(x.innerHTML);  }</script> </head> <body><h1 id="myHeader" onclick="getValue()">PaparSayapadakotakelert!</h1> </body> </html> Example

  10. InnerHTML <html> <body> <p id="intro">Intoduction to DOM</p> <script type="text/javascript"> txt=document.getElementById("intro").innerHTML; document.write("<h2>The text from the intro paragraph: <span style = \"color: magenta\"> " + txt + "</span></h2>"); </script> </body> </html> Example

  11. getElementsByName() <html> <head> <script type="text/javascript"> function getElements() { var x=document.getElementsByName("list"); alert(x.length); } </script></head> <body> <ul> <li name="list"><a href=" ">FTSM</a></li> <li name="list"><a href=" ">FST</a></li> <li name="list"><a href=" ">FSKK</a></li> <li name="list"><a href=" ">FPI</a></li> <li name="list"><a href=" ">FPend</a></li></ul> <input type="button" onclick="getElements()" value="How many elements named 'list?" /> </body></html> Example

  12. getElementsByTagName() <html><head> <script type="text/javascript"> function getElements() { var x=document.getElementsByTagName("li"); alert(x.length); } </script></head> <body> <ul> <li><a href=" ">FTSM</a></li> <li><a href=" ">FST</a></li> <li><a href=" ">FSKK</a></li> <li><a href=" ">FPI</a></li> <li><a href=" ">FPend</a></li> </ul> <input type="button" onclick="getElements()" value="How many list items?" /> </body></html> Example

  13. Retrieving Child element • If an element contains other elements then these elements are its child • childNodesis a list of all the first-level child nodes of the element – it does not cascade down into deeper levels • A child element of the current element can be access via the array index or the item() method • yourElement.firstChild @ yourElement.lastChild yourElement.childNodes[0] @ yourElement.childNodes[yourElement.childNp.length-1) • To check whether an element has any children by calling the method hasChildNodes(), which returns a Boolean value.

  14. childNodes() <html> <body> <p id="intro">Web Programming</p> <div id="main"> <ul id = "nav"> NAMA PROGRAM <li>SainsMaklumat</li> <li>Multimedia</li> <li>KomputeranIndustri</li> <li>SainsKomputer</li> <li>PengurusanSistem</li> </ul></div> <script type="text/javascript"> x=document.getElementById("nav").childNodes[1]; document.write("First paragraph text: " + x.innerHTML); </script> </body> </html> Example

  15. parentNode • Returns the parent element of the current node in the DOM hierarchy.

  16. parentNode <html> <body> <ul> NAMA PROGRAM <li>SainsMaklumat</li> <li>Multimedia</li> <li>KomputeranIndustri</li> <li>SainsKomputer</li> <li>PengurusanSistem</li> </ul> <script type="text/javascript"> txt=document.getElementsByTagName("li")[3].parentNode; document.write("<p> Memaparkan <i>Parent</i> bersertaanak: " + txt.innerHTML + "</p>"); </script> </body> </html> Example

  17. firstChild, lastChild • The firstChild property retrieves the first item from the childNodes collection. • Similarly, the lastChild property returns the last item from the childNodes collection.

  18. firstChild <html><head> <script type="text/javascript"> function GetFirstText () { varselectObj = document.getElementById ("mySelect"); alert (selectObj.firstChild.text); } </script> </head> <body> <button onclick="GetFirstText ();">Get the text of the first child!</button> <select id="mySelect" multiple="multiple“><option>FTSM</option> <option>FST</option> <option>FSSK</option> <option>FPI</option> <option>FPend</option> </select> </body></html> alert (selectObj.childNodes[0].text); alert (selectObj.childNodes[0].innerHTML); Example

  19. lastChild <html><head> <script type="text/javascript"> function GetFirstText () { varselectObj = document.getElementById ("mySelect"); alert (selectObj.lastChild.text); } </script> </head> <body> <button onclick="GetLastText ();">Get the text of the last child!</button> <select id="mySelect" multiple="multiple"><option>FTSM</option> <option>FST</option> <option>FSSK</option> <option>FPI</option> <option>FPend</option></select> </body></html> alert (selectObj.childNodes[childNodes.length - 1].text); alert (selectObj.childNodes[childNodes.length - 1].innerHTML); Example

  20. nextSibling • Returns a reference to the next child of the current element's parent. • In other words, the nextSibling property returns the element that immediately follows the current element in the childNodes collection of the current element's parent. • Returns a reference to the next sibling or null if it does not exist.

  21. nextSibling <html><head> <script type="text/javascript“> function GetNextNode () { varparentElem = document.getElementById ("navigation"); secondElem = parentElem.childNodes[1]; alert ("The value of the first node: " + secondElem.innerHTML); prevElem = secondElem.nextSibling; alert ("The value of the next node: " + prevElem.innerHTML); prev1Elem = prevElem.nextSibling; alert ("The value of the next node: " + prev1Elem.innerHTML); } </script></head> <body><div id="header“><div align="center"><imgsrc="ukm.jpg" alt="Fakulti" width="208" height="144"></div></div> <h4>FakultiTeknologidanSainsMaklumat</h4> <div id="navigation“> <ul>PUSAT PENGAJIAN TEKNOLOGI MAKLUMAT <li>SainsMaklumat</li><li>Multimedia</li><li>KomputeranIndustri</li></ul> <ul>PUSAT PENGAJIAN SAINS KOMPUTER <li>SainsKomp.</li><li>Peng.Sistem</li><li>KecerdasanBuatan</li></ul></div> <button onclick="GetNextNode ()">Get Next Node!</button><br /> </body></html> Example

  22. Node Properties • Once reached a wanted node, you can read out its properties • nodeType stores the type of the node (1 for element, 3 for text) • nodeName stores the name of the node (either the element name or #textNode) • nodeValue stores the value of the node (null for element nodes and the text for text nodes)

  23. nextElementSibling • Returns a reference to the next child element of the current element's parent. • The next sibling node and the next sibling element can be different. A node is an element node if it's nodeType is 1 (Node.ELEMENT_NODE). Text nodes and comment nodes are not element nodes. If you need the next sibling node of an element, use the nextSibling property. • Similarly to the nextElementSibling property, the previousElementSibling property returns the previous sibling element of an element, furthermore the firstElementChild and lastElementChild properties return the first and last child element of an element.

  24. Content <body> <ol id="navigation">FAKULTI TEKNOLOGI DAN TEKNOLOGI MAKLUMAT <li>SainsMaklumat</li> <li>Multimedia</li> <li>KomputeranIndustri</li> <li>SainsKomputer</li> <li>PengurusanSistem</li> <li>KecerdasanBuatan</li> </ol> <button onclick="GetListItems ();">Get the list items!</button> </body> </html>

  25. nextElementSibling <html> <head> <script type="text/javascript"> function GetListItems () { var list = document.getElementById ("navigation"); if (list.firstElementChild === undefined) { var child = list.firstChild; while (child) { if (child.nodeType == 1 /*Node.ELEMENT_NODE*/) { alert (child.innerHTML); } child = child.nextSibling; } } else { var child = list.firstElementChild; while (child) { alert (child.innerHTML); child = child.nextElementSibling; } } } </script></head> Example

  26. Creating New Nodes • New nodes can be create using • document.createElement(element) creates a new element node • document.createTextNode(text) creates a new text node

  27. Adding New Nodes to the Document • node.removeChild(oldNode) removes the child oldNode from node • node.appendChild(oldNode) adds newNodes as a new (last) child node to node • node.insertBefore(newNode, oldNode) inserts newNode as a new child node of node before oldNode • node.replaceChild(newNode, oldNode) replaces the child node oldNode of node with newNode

  28. removeChild <html><head> <script type="text/javascript"> function changeContent() { var x = document.getElementById("nav").firstChild; x.parentNode.removeChild(x); } </script></head> <body> <ul id = "nav"> <li><a href="tp.html">SainsMaklumat</a></li> <li><a href="th.html">Multimedia</a></li> <li><a href="tr.html">KomputeranIndustri</a></li> <li><a href="tk.html">SainsKomputer</a></li> <li><a href="ts.html">PengurusanSistem</a></li> </ul> <form> <input type="button" onclick="changeContent()" value="Change content"> </form> </body></html> Example

  29. appendChild <html><head> <script type="text/javascript"> function changeContent() { var x = document.getElementById("nav"); var a = document.createElement("li"); x.appendChild(a); } </script></head> <body> <ul id = "nav"> <li><a href="tp.html">SainsMaklumat</a></li> <li><a href="th.html">Multimedia</a></li> <li><a href="tr.html">KomputeranIndustri</a></li> <li><a href="tk.html">SainsKomputer</a></li> <li><a href="ts.html">PengurusanSistem</a></li> </ul> <form> <input type="button" onclick="changeContent()" value="Change content"> </form></body> Example

  30. insertBefore <html><head> <script type="text/javascript"> function changeContent() { var Parent = document.getElementById("nav"); varNewLI = document.createElement("li"); NewLI.innerHTML = "KecerdasanBuatan"; Parent.insertBefore(NewLI, Parent.firstChild); } </script></head> <body> <ul id = "nav"> <li><a href="tp.html">SainsMaklumat</a></li> <li><a href="th.html">Multimedia</a></li> <li><a href="tr.html">KomputeranIndustri</a></li> <li><a href="tk.html">SainsKomputer</a></li> <li><a href="ts.html">PengurusanSistem</a></li> </ul> <form><input type="button" onclick="changeContent()" value="Change content“> </form> </body></html> Example

  31. replaceChild <html><head> <script type="text/javascript"> function MakeFirst(button) { var container = document.getElementById ("nav"); varfirstButton = container.getElementsByTagName ("button")[0]; if (button != firstButton) { container.replaceChild (button, firstButton); container.insertBefore (firstButton, button.nextSibling); } } </script></head> <body> <div id = "nav"> <button onclick="MakeFirst (this)" style="color:red">SainsMaklumat</button> <button onclick="MakeFirst (this)" style="color:#336633 ">Multimedia</button> <button onclick="MakeFirst (this)" style="color:blue">KomputeranIndustri</button> <button onclick="MakeFirst (this)" style="color:black">SainsKomputer</button> </div> </body></html> Example

  32. Basic DOM functionality (Part 1 of 6). 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 <!-- Fig. 12.2: dom.html --> 6 <!-- Basic DOM functionality. --> 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Basic DOM Functionality</title> 10 <style type = "text/css"> 11 h1, h3 { text-align: center; 12 font-family: tahoma, geneva, sans-serif } 13 p { margin-left: 5%; 14 margin-right: 5%; 15 font-family: arial, helvetica, sans-serif } 16 ul { margin-left: 10% } 17 a { text-decoration: none } 18 a:hover { text-decoration: underline } 19 .nav { width: 100%; 20 border-top: 3px dashed blue; 21 padding-top: 10px } 22 .highlighted { background-color: yellow } 23 .submit { width: 120px } 24 </style> 25 <script type = "text/javascript"> 26 <!-- 27 varcurrentNode; // stores the currently highlighted node 28 varidcount = 0; // used to assign a unique id to new elements 29 Creates a class to highlight text

  33. Basic DOM functionality (Part 2 of 6). Calls function switchTo if the object can be found 30 // get and highlight an element by its id attribute 31 function byId() 32 { 33 var id = document.getElementById( "gbi" ).value; 34 var target = document.getElementById( id ); 35 36 if ( target ) 37 switchTo( target ); 38 } // end function byId 39 40 // insert a paragraph element before the current element 41 // using the insertBefore method 42 function insert() 43 { 44 varnewNode = createNewNode( 45 document.getElementById( "ins" ).value ); 46 currentNode.parentNode.insertBefore( newNode, currentNode ); 47 switchTo( newNode ); 48 } // end function insert 49 50 // append a paragraph node as the child of the current node 51 function appendNode() 52 { 53 varnewNode = createNewNode( 54 document.getElementById( "append" ).value ); 55 currentNode.appendChild( newNode ); 56 switchTo( newNode ); 57 } // end function appendNode 58 Calls function createNewNode to make a new p node with the text in the ins text field Inserts newNode as a child of the parent node, directly before currentNode Highlights newNode with function switchTo Inserts newNode as a child of the current node

  34. Basic DOM functionality (Part 3 of 6). Gets the parent of currentNode, then inserts newNode into its list of children in place of currentNode 59 // replace the currently selected node with a paragraph node 60 function replaceCurrent() 61 { 62 varnewNode = createNewNode( 63 document.getElementById( "replace" ).value ); 64 currentNode.parentNode.replaceChild( newNode, currentNode ); 65 switchTo( newNode ); 66 } // end function replaceCurrent 67 68 // remove the current node 69 function remove() 70 { 71 if ( currentNode.parentNode == document.body ) 72 alert( "Can't remove a top-level element." ); 73 else 74 { 75 varoldNode = currentNode; 76 switchTo( oldNode.parentNode ); 77 currentNode.removeChild( oldNode ); 78 } 79 } // end function remove 80 81 // get and highlight the parent of the current node 82 function parent() 83 { 84 var target = currentNode.parentNode; 85 86 if ( target != document.body ) 87 switchTo( target ); 88 else 89 alert( "No parent." ); 90 } // end function parent Ensures that top-level elements are not removed Highlights oldNode’s parent Removes oldNode from the document Gets the parent node Makes sure the parent is not the body element

  35. Basic DOM functionality (Part 4 of 6). Creates (but does not insert) a new p node Creates a unique id for the new node 91 92 // helper function that returns a new paragraph node containing 93 // a unique id and the given text 94 function createNewNode( text ) 95 { 96 varnewNode = document.createElement( "p" ); 97 nodeId = "new" + idcount; 98 ++idcount; 99 newNode.id = nodeId; 100 text = "[" + nodeId + "] " + text; 101 newNode.appendChild(document.createTextNode( text ) ); 102 return newNode; 103 } // end function createNewNode 104 105 // helper function that switches to a new currentNode 106 function switchTo( newNode ) 107 { 108 currentNode.className = ""; // remove old highlighting 109 currentNode = newNode; 110 currentNode.className = "highlighted"; // highlight new node 111 document.getElementById( "gbi" ).value = currentNode.id; 112 } // end function switchTo 113 // --> 114 </script> 115 </head> 116 <body onload = "currentNode = document.getElementById( 'bigheading' )"> 117 <h1 id = "bigheading" class = "highlighted"> 118 [TajukBesar] DHTML Object Model</h1> 119 <h3 id = "smallheading">[Sub Tajuk] Element Functionality</h3> Creates new text node with the contents of variable text, then inserts this node as a child of newNode Changes class attribute to unhighlight old node Highlights currentNode Assigns currentNode’sid to the input field’s value property

  36. Basic DOM functionality (Part 5 of 6). 120 <p id = "para1">[para1] The Document Object Model (DOM) allows for 121 quick, dynamic access to all elements in an XHTML document for 122 manipulation with JavaScript.</p> 123 <p id = "para2">[para2] For more information, check out the 124 "JavaScript and the DOM" section of Deitel's 125 <a id = "link" href = "http://www.deitel.com/javascript"> 126 [link] JavaScript Resource Center.</a></p> 127 <p id = "para3">[para3] The buttons below demonstrate:(list)</p> 128 <ul id = "list"> 129 <li id = "item1">[item1] getElementById and parentNode</li> 130 <li id = "item2">[item2] insertBefore and appendChild</li> 131 <li id = "item3">[item3] replaceChild and removeChild </li> 132 </ul> 133 <div id = "nav" class = "nav"> 134 <form onsubmit = "return false" action = ""> 135 <table> 136 <tr> 137 <td><input type = "text" id = "gbi" 138 value = "bigheading" /></td> 139 <td><input type = "submit" value = "Get By id" 140 onclick = "byId()" class = "submit" /></td> 141 </tr><tr> 142 <td><input type = "text" id = "ins" /></td> 143 <td><input type = "submit" value = "Insert Before" 144 onclick = "insert()" class = "submit" /></td> 145 </tr><tr> 146 <td><input type = "text" id = "append" /></td> 147 <td><input type = "submit" value = "Append Child" 148 onclick = "appendNode()" class = "submit" /></td> 149 </tr><tr>

  37. Basic DOM functionality (Part 6 of 6). 150 <td><input type = "text" id = "replace" /></td> 151 <td><input type = "submit" value = "Replace Current" 152 onclick = "replaceCurrent()" class = "submit" /></td> 153 </tr><tr><td /> 154 <td><input type = "submit" value = "Remove Current" 155 onclick = "remove()" class = "submit" /></td> 156 </tr><tr><td /> 157 <td><input type = "submit" value = "Get Parent" 158 onclick = "parent()" class = "submit" /></td> 159 </tr> 160 </table> 161 </form> 162 </div> 163 </body> 164 </html> View at browser

  38. Access the Data <form name="personal" action="something.php onsubmit="return checkscript()"> <input type=text size=20 name=name> <input type=text size=20 name=address> <input type=text size=20 name=city> </form> document.personal.name document.personal.address document.personal.city document.forms[0].elements[0] document.forms[0].elements[1] document.forms[0].elements[2] user_input = document.forms[0]. elements[0] .value;

  39. <script type="text/javascript"> function findtheone( ) { varwhichitem = 0; while (whichitem < document.form02.field01.length) { if (document.form02.field01[whichitem].checked) { window.alert('You picked item number ' + (whichitem + 1)); } whichitem++; } } </script> <form class="example" name="form02" method="" action=""> <p> Pick an option ... [<input type="radio" name="field01" value="item1" /> 1] [<input type="radio" name="field01" value="item2" /> 2] [<input type="radio" name="field01" value="item3" /> 3] [<input type="radio" name="field01" value="item4" /> 4] </p> <p> And click the button: <input type="button" name="field02" value="Find the One" onclick="findtheone( );" /> <input type="button" name="field03" value="Set to One" onclick="document.form02.field01[0].checked='true';" /> </p> Example

  40. Other Example <html><head> <script type="text/javascript"> function setSpace() { document.getElementById("ftsm").hspace="80"; document.getElementById("ftsm").vspace="80"; } </script></head> <body> <img id="ftsm" src="ftsm.jpg" alt="FTSM" /> <p>SainsMaklumat : Melalui program ini, disiplin-disiplinseperticapaianmaklumat, enjingelintar, pembrokeranmaklumat, agenmaklumatcerdasdanorganisasimaklumatmerupakansebahagiandaripadateraskepada program ini</p> <input type="button" onclick="setSpace()" value="Set hspace and vspace" /> </body> </html> Example

  41. <html><head> <script type="text/javascript"> var inputs = 0; function addContact(){ var table = document.getElementById('contacts'); vartr = document.createElement('TR'); var td1 = document.createElement('TD'); var td2 = document.createElement('TD'); var td3 = document.createElement('TD'); var inp1 = document.createElement('INPUT'); var inp2 = document.createElement('INPUT'); if(inputs>0){ varimg = document.createElement('IMG'); img.setAttribute('src', 'del2.jpg'); img.onclick = function(){ removeContact(tr); } td1.appendChild(img); } inp1.setAttribute("Name", "Name" +inputs); inp2.setAttribute("Name", "Email"+inputs); table.appendChild(tr); tr.appendChild(td1); tr.appendChild(td2); tr.appendChild(td3); td2.appendChild(inp1); td3.appendChild(inp2); inputs++; }

  42. function removeContact(tr){ tr.parentNode.removeChild(tr); } </script> </head> <body> <table> <tbody id="contacts"> <tr> <td colspan="3"> <a href="javascript:addContact();">Add a Contact</a></td> </tr> <tr> <td></td> <td>Name</td> <td>Email</td> </tr> </tbody> </table> </body></html> Example

  43. Reference : http://help.dottoro.com/ • DHTML objects • DHTML properties • DHTML methods http://www.howtocreate.co.uk/tutorials/javascript/domstructure

More Related