DOM

24
Ajax, JavaScript and PHP Chapter 5 – Document Object Model (DOM)

Transcript of DOM

Page 1: DOM

Ajax, JavaScript and PHP

Chapter 5 – Document Object Model (DOM)

Page 2: DOM

JavaScript Supports three kinds of objects

• Built-in objects: are built in to the JavaScript language. (Date, Array, String)

• DOM (Document Object Model): objects represent various components of the browser and the current HTML document.

• Custom objects: objects you created.• NOTE: DOM is not part of the JavaScript language. It

is an API (Application Programming Interface) build in to the browser.

• NOTE: The window object is the parent object for all of the objects. (See next diagram)

Page 3: DOM

The DOM object hierarchy

Window Object(Global Object)

document object(DOM)

location object

history object(array)

navigator object

self

opener

alert()back()blur()

clearInterval()clearTimeout()

close()confirm()focus()

forward()home()open()print()

prompt()setInterval()setTimeout()

stop()

Window Properties

Window Methods

Document Object Collection:images[]forms[]links[]

anchors[]

Document Object Properties:lastModified

titleURL

Document Object Methods:close()

getElementById()getElementsByName()

getElementsByTagname()open()write()

Page 4: DOM

HTML Document Object Model (HTML DOM)

Page 5: DOM

Scripting Documents• Every web browser window (or frame) displays an HTML document. The

Window object that represents that window has a document property that refers to a Document object.

• HTML documents can contain text, images, hyperlinks, form elements, and so on.

• JavaScript code can access and manipulate the objects that represent each document element.

• A Document Object Model, or DOM, is an API that defines how to access the objects that compose a document.

• The W3C defines a standard DOM that is reasonably well supported in all modern web browsers.

• In the early days, Netscape 2 and 3 supported a simple DOM that provided access only to special document elements such as links, images, and form elements. This legacy DOM was adopted by all browser vendors and has been formally incorporated into the W3C standard as the “Level 0” DOM.

Page 6: DOM

Scripting Documents

• With IE 4, has a new DOM, it allowed access to all elements in a document. Microsoft’s API is known as the IE 4 DOM. It was never standardized, and IE 5 and later adopted the W3C DOM.

• Netscape 4 based on dynamically positioned scriptable elements known as layers. It was supported only in Netscape 4 and dropped from the Mozilla and Firefox browsers.

• The W3C DOM standard, or simply, DOM, adopted IE and Netscape DOM.

Page 7: DOM

Dynamic Document Content• Let’s exploring the Document object with its write() method. This method is part of

the legacy DOM:<script>var today = new Date();document.write(“<p>Document access on: “ + today.toString());</script>

• You might create a pop-up window and write some HTML to it with code like this:function hello() {

var w = window.open();var d = w.document;d.open(); //open a new document – optionald.write(“<h1>Hello world!</h1>”);d.close();

}• If you call the write() method on a document that has already been closed,

JavaScript implicitly opens a new HTML document.

Page 8: DOM

Document Properties• Legacy DOM Document object properties:

bgColor (deprecated) cookie domain lastModified location referrer title URL

• You can place code like this to the bottom of each web document:<hr>document: <script>document.write(document.title);</script><br>URL: <script>document.write(document.URL);</script><br>Last Update: <script>document.write(document.lastModified);</script>

Page 9: DOM

Legacy DOM: Document Object Collections

• The Document Object Collections, are array-valued properties, are the heart of the legacy DOM. They are the properties that give you access to certain especial elements of the document: anchors[ ] applets[ ] forms[ ] images[ ] links[ ]

• Their elements are in the same order as in the document source code. document.forms[0] refers to the first <form> tag in the document.

Page 10: DOM

Naming Document Objects• In the legacy DOM, with the name attribute, you can assign names to important

document elements and to refer to those elements by name:<form name=“f1”><input type=“button” value=“Push Me”></form>

• Assuming that the <form> is the first one in the document:document.forms[0] // refer to the form by positiondocument.f1 // refer to the form by namedocument.forms[“f1”] // refer to the form as array index

• Setting the name attribute of a <form>, <img>, or <applet> (but not of <a> and <link>>) also makes the corresponding Form, Image, or Applet object accessible as a named property of the document object itself. Thus, you can also refer to the form as:

document.f1• You have a form that looks like this:

<form name=“shipping”><input type=“text” name=“zipcode”>

</form>/* you can refer to the text input field element as : */document.shipping.zipcode

Page 11: DOM

Overview of the W3C DOM• HTML documents have a hierarchical structure of nested tags

that is represented in the DOM as a tree of objects. The tree representation of an HTML document contains nodes representing HTML tags or elements, such as <body> and <p>.

• Consider the following simple HTML document:<html>

<head><title>Simple Document</title></head><body>

<h1>An HTML Document</h1><p>This is a <i>simple</i> document.

</body></html>

Page 12: DOM

DOM Levels and Features

• There are two versions, or “levels” of the DOM standard.

• DOM Level 1 was standardized in October 1998

• DOM Level 2 was standardized in November 2000

• DOM Level 3 features are not yet widely supported by web browsers.

Page 13: DOM

Finding Elements in a Document

• When programming with the DOM API, it is quite common to need a particular node within the document or a list of nodes of a specific type within the document.

• The Document object is the root of every DOM tree, but it does not represent an HTML element in that tree.

• The document.documentElement property refers to the <html> tag that serves as the root element of the document.

• The body property of the HTML Document object is a convenient special-case property:

document.getElementsByTagName(“body”)[0]• This expression calls the Document object’s getElementsByTagName()

method and selects the first element of the returned array.• You can use getElementsByTagName() to obtain a list of any type of HTML

element.var tables = document.getElementsByTagName(“table”);alert(“This document contains “ + tables.length + “ tables”);

Page 14: DOM

Finding Elements in a Document

• If you pass the special string “*” to getElementsByTagName(), it returns a list of all elements in the document, in the order in which they appear. (this special usage is not supported in IE 5 and IE 5.5, see IE specific HTMLDocument.all[ ])

• To get the fourth paragraph in a document:var myParagraph = document.getElementsByTagName(“p”)[3];

• This is not the best nor the most efficient technique. • It is best to give elements an id attribute, then look up your

desired element by its ID.<p id = “specialParagraph”>var myParagraph = document.getElementById(“specialParagraph”);

Page 15: DOM

Window Object – a clock• <html>• <head>• <script language=“JavaScript”>• function startTime()• {• var today=new Date();• var h=today.getHours();• var m=today.getMinutes();• var s=today.getSeconds();• document.getElementById('txt').innerHTML=h+":"+m+":"+s;• t=setTimeout('startTime()',500);• }• </script>• </head>

• <body onload="startTime()">• <div id="txt"></div>• </body>• </html>

Page 16: DOM

Window Object - URL• <html>• <head>• <script type="text/javascript">• function currLocation()• {• alert(window.location);• }

• function newLocation()• {• window.location="http://www.ccsf.edu";• }• </script>• </head>

• <body>• <input type="button" onclick="currLocation()" value="Show current URL">• <input type="button" onclick="newLocation()" value="Change URL">• </body>• </html>

Page 17: DOM

Window Object – Reload and Print• <html>• <head>• <script type="text/javascript">• function reloadPage()• {• window.location.reload();• }• function printpage()• {• window.print();• }

• </script>• </head>• <body>

• <input type="button" value="Reload page" onclick="reloadPage()" />• <input type="button" value=“Print this page" onclick=“printpage()" />

• </body>• </html>

Page 18: DOM

Document Object – Title, URL• <html>• <head>• <title>My title</title>• </head>

• <body>• <script type="text/javascript">• document.writeln(“Document Title: “, document.title);• document.writeln(“Document URL: “, document.URL);• </script>• </body>

• </html>

Page 19: DOM

Document Object - 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()">This is a header</h1>• <p>Click on the header to alert its value</p>

• </body>• </html>

• Result: will display This is a header

Page 20: DOM

Document Object - getElementsByName

• <html>• <head>• <script type="text/javascript">• function getElements()• {• var x=document.getElementsByName("myInput");• alert(x.length);• }• </script>• </head>

• <body>• <input name="myInput" type="text" size="20" /><br />• <input name="myInput" type="text" size="20" /><br />• <input name="myInput" type="text" size="20" /><br />• <br />• <input type="button" onclick="getElements()" value="How many elements named 'myInput'?" />• </body>

• </html>

• Result: will display 3

Page 21: DOM

Anchor Object – href, target• <html>• <head>• <script type="text/javascript">• function changeLink()• {• document.getElementById('myAnchor').innerHTML="Visit CCSF";• document.getElementById('myAnchor').href="http://www.ccsf.edu";• document.getElementById('myAnchor').target="_blank";• }• </script>• </head>

• <body>• <a id="myAnchor" href="http://www.microsoft.com">Visit Microsoft</a>• <input type="button" onclick="changeLink()" value="Change link">• <p>In this example we change the text and the URL of a hyperlink. We also change the target attribute.• The target attribute is by default set to "_self", which means that the link will open in the same window.• By setting the target attribute to "_blank", the link will open in a new window.</p>• </body>

• </html>

Page 22: DOM

Image Object – resize, change src• <html>• <head>• <script type="text/javascript">• function changeSize()• {• document.getElementById(“ccsf").height="250";• document.getElementById(“ccsf").width="300";• }• function changeSrc()• {• document.getElementById(“ccsf").src=“colan.gif";• }• </script>• </head>• <body>• <img id=“ccsf" src=“logo_01.gif" width="107" height="98" />• <br /><br />• <input type="button" onclick="changeSize()" value="Change height and width of image">• <input type="button" onclick="changeSrc()" value="Change image">• </body>• </html>

Page 23: DOM

Table Object – update cells• <html>• <head>• <script type="text/javascript">• function changeContent()• {• var x=document.getElementById('myTable').rows[0].cells;• x[0].innerHTML="NEW CONTENT";• x[1].innerHTML="NEW TOO";• }• </script>• </head>• <body>• <table id="myTable" border="1">• <tr><td>Row1 cell1</td><td>Row1 cell2</td></tr>• <tr><td>Row2 cell1</td><td>Row2 cell2</td></tr>• <tr><td>Row3 cell1</td><td>Row3 cell2</td></tr>• </table>• <form>• <input type="button" onclick="changeContent()" value="Change content">• </form>• </body>• </html>

Page 24: DOM

Table Object – display cell• <html>• <head>• <script type="text/javascript">• function dsptxt(id)• {• alert(document.getElementById(id).innerHTML);• }• </script>• </head>• <body>• <table id="mytable" border="2">• <tr><td id="cell1"><a href="javascript:dsptxt('cell1');">Cell 1 data</a></td>• <td id="cell2"><a href="javascript:dsptxt('cell2');">Cell 2 data</a></td></tr>• <tr><td id="cell3"><a href="javascript:dsptxt('cell3');">Cell 3 data</a></td>• <td id="cell4"><a href="javascript:dsptxt('cell4');">Cell 4 data</a></td></tr>• <tr><td id="cell5"><a href="javascript:dsptxt('cell5');">Cell 5 data</a></td>• <td id="cell6"><a href="javascript:dsptxt('cell6');">Cell 6 data</a></td></tr>• <tr><td id="cell7"><a href="javascript:dsptxt('cell7');">Cell 7 data</a></td>• <td id="cell8"><a href="javascript:dsptxt('cell8');">Cell 8 data</a></td></tr>• </table>• </body>• </html>