Sunteți pe pagina 1din 32

CSE 130

Programming Language Principles & Paradigms

Lecture #

JavaScript Overview Part II

CSE 130

Programming Language Principles & Paradigms

Lecture #

Function Basics
Functions are used to create code fragments that can be used over and over again. Hopefully, these are abstract reusable components, but this is up to the programmer.
function functionname(parameterlist) { statement(s) } where
Functioname must be well-formed JavaScript identifier Parameterlist is a list of JavaScript identifiers separated by commas. The list may also be empty

CSE 130

Programming Language Principles & Paradigms

Lecture #

Function Example 1
Simple function with no parameters
function sayHello() { alert("Hello there"); } sayHello(); // invoke the function

Note: You generally will be unable to call a function before it is defined. This suggests that you should define your functions in the <head> of your (X)HTML document. However, in some JavaScript implementations you can forward reference with the same <script> block.

CSE 130

Programming Language Principles & Paradigms

Lecture #

Function Example 2: Parameters


function sayHello(name) { if (name != " ") alert("Hello there "+name); else alert("Dont be shy. "); }

/* Make some calls */ sayHello("George"); sayHello();

CSE 130

Programming Language Principles & Paradigms

Lecture #

Example 3: Multiple Parameters & Return function addThree(arg1, arg2, arg3) { return (arg1 + arg2 + arg3); }

var x = 5, y = 7, result; result = addThree(x,y,11); alert(result);

CSE 130

Programming Language Principles & Paradigms

Lecture #

Example 4: Multiple Returns function myMax(arg1, arg2) { if (arg1 >= arg2) return arg1 else return arg2; } Note: Functions always return some value whether or not a return is explicitly provided. Usually it is a value of undefined.

CSE 130

Programming Language Principles & Paradigms

Lecture #

Parameter Passing
Primitive Data types are passed by value, in other words a copy of the data is made and given to the function
function fiddle(arg1) { arg1 = 10; document.write("In fiddle arg1 = "+arg1+"<br />"); } var x = 5; document.write("Before function call x = "+x+"<br />"); fiddle(x); document.write("After function call x = "+x+"<br />");

CSE 130

Programming Language Principles & Paradigms

Lecture #

Parameter Passing 2
Composite types are passed by reference in JS
function fiddle(arg1) { arg1[0] = "changed"; document.write("In fiddle arg1 = "+arg1+"<br />"); } var x = ["first", "second", "third"]; document.write("Before function call x = "+x+"<br />"); fiddle(x); document.write("After function call x = "+x+"<br />");

CSE 130

Programming Language Principles & Paradigms

Lecture #

Global and Local Variables


A global variable is one that is known throughout a document A local variable is limited to the particular function it is defined in All variables defined outside a function are global by default Variables within a function defined using a var statements are local

CSE 130

Programming Language Principles & Paradigms

Lecture #

Global and Local Example


// Define x globally var x = 5; function myFunction() { document.write("Entering function<br /> x="+x+ <br />"); document.write("Changing x <br />"); x = 7; document.write("x="+x+"<br /> Leaving function<br />"); } document.write("Starting Script<br />"); document.write("x="+x+"<br />"); myFunction(); document.write("Returning from function<br />"); document.write("x="+x+"<br />"); document.write("Ending Script");

CSE 130

Programming Language Principles & Paradigms

Lecture #

Local Variable Example


function myFunction() { var y=5; // define a local variable document.write("Within function y="+y); } myFunction(); document.write("After function y="+y); Note: This example will throw an error, but thats the point. You could use an if statement to avoid problems like if (window.y) document.write("After function y="+y); else document.write("Y is undefined");

CSE 130

Programming Language Principles & Paradigms

Lecture #

Mask Out
Be careful when you have local and global variables of the same name, you may get an undesirable effect called mask out.
var x = "As a global I am a string"; function maskDemo() { var x = 5; document.write("In function maskDemo x="+x+"<br />"); } document.write("Before function call x="+x+"<br />"); maskDemo(); document.write("After function call x="+x+"<br />");

CSE 130

Programming Language Principles & Paradigms

Lecture #

Local Functions
function testFunction() { function inner1() { document.write("testFunction-inner1<br />"); } function inner2() { document.write("testFunction-inner2<br />"); } document.write("Entering testFunction<br />"); inner1(); inner2(); document.write("Leaving testFunction<br />"); } document.write("About to call testFunction<br />"); testFunction(); document.write("Returned from testFunction<br />"); /* Call inner 1 or inner2 here and error */ inner1();

CSE 130

Programming Language Principles & Paradigms

Lecture #

Functions as Objects
Like nearly everything in JS, functions are objects and can be created and accessed as such
var sayHello = new Function("alert('Hello there');"); sayHello();

This allows us to even reuse functions in an interesting way.


var sayHelloAgain = sayHello; sayHelloAgain();

CSE 130

Programming Language Principles & Paradigms

Lecture #

Functions as Objects
You can also define functions with parameters in this fashion.
var sayHello2 = new Function("msg","alert('Hello there '+msg);"); sayHello2('Thomas');

The general syntax is


var functionName = new Function("argument 1","argument n", "statements for function body");

CSE 130

Programming Language Principles & Paradigms

Lecture #

Useful Function Features


As objects you can reference the length of functions, thus find out the number of arguments function myFunction(arg1,arg2,arg3) { // do something } alert("Number of parameters for myFunction = "+myFunction.length);

CSE 130

Programming Language Principles & Paradigms

Lecture #

Arguments and Length


You can examine not just defined arguments but actual passed parameters
function myFunction() { document.write("Number of parameters defined = "+myFunction.length+"<br />"); document.write("Number of parameters passed = "+myFunction.arguments.length+"<br />") for (i=0;i<arguments.length;i++) document.write("Parameter "+i+" = "+myFunction.arguments[i]+"<br />") } myFunction(33,858,404);

CSE 130

Programming Language Principles & Paradigms

Lecture #

Variable Arguments
Given arguments and length you can write more adaptive functions that take variable arguments
function sumAll() { var total=0; for (var i=0; i< sumAll.arguments.length; i++) total+=sumAll.arguments[i]; return(total); } alert(sumAll(3,5,3,5,3,2,6));

CSE 130

Programming Language Principles & Paradigms

Lecture #

Literal and Anonymous Functions


function simpleRobot(robotName) { this.name = robotName; this.sayHi = function () { alert('Hi my name is '+this.name); }; this.sayBye = function () { alert('Bye!'); }; this.sayAnything = function (msg) { alert(this.name+' says '+msg); }; } fred.sayHi(); fred.sayAnything("I don't know what to say"); fred.sayBye();

CSE 130

Programming Language Principles & Paradigms

Lecture #

Recursive Functions
JS supports recursive functions that call themselves Factorial n! = n*(n-1)*(n-2) * 1
function factorial(n) { if (n == 0) return 1; else return n* factorial(n 1); } alert(factorial(5)); Demo this with negative value in Internet Explorer

CSE 130

Programming Language Principles & Paradigms

Lecture #

Objects in JavaScript
Objects in JavaScript fall into four groups:
Built-in objects (ex. String, Date, Array, etc.) Browser objects (ex. Window, Navigator) Document objects (ex. Document, document.forms[], etc.) User-defined objects

User defined objects are often not used by novice JavaScript programmers but become quite important as you build larger and larger Web applications

CSE 130

Programming Language Principles & Paradigms

Lecture #

Object Creation
Use the new( ) operator along with the appropriate constrictor function
var city = new String(); var city = new String(San Diego); var city2 = San Diego; alert(typeof city); alert(typeof city2);

Of course we will often be making our own objects


var city = new Object(); city.name = San Diego; city.sunny = true;

CSE 130

Programming Language Principles & Paradigms

Lecture #

Object Destruction
We dont have to do much as within browser implementation of JavaScript garbage collection cleans up unused object references we may have
var myString = new String(Larry Fine); myString = new String(Moe Howard); // Larry Fine string eventually garbage collected

Better to hint to the browser you are done with memory though.
var city = new Object(); city = null; // hint to garbage collector

CSE 130

Programming Language Principles & Paradigms

Lecture #

Properties
A property is named data contained in an object
var myString = new String('hello there'); alert(myString.length);

Properties that are not set return undefined Instance properties can be added to a particular object and deleted as well
var myString = new String('hi'); myString.simpleExample = true; alert(myString.simpleExample); delete myString.simpleExample; alert(myString.simpleExample); // undefined

CSE 130

Programming Language Principles & Paradigms

Lecture #

Array Style Property Access


You can also use [ ] to access a property of an object by name
var myString = new String('hi'); alert(myString['length']); myString['simpleExample']=true; alert(myString['simpleExample']); delete(myString['simpleExample']); alert(myString['simpleExample']);

The main uses of this style of syntax is when the property name is a variable or if the property name contains spaces.

CSE 130

Programming Language Principles & Paradigms

Lecture #

Methods
Object properties that are functions are called methods You can use the standard . operator as well as the array syntax to access a method but add the ( ) to invoke the method
var myString = new String("Hi there"); alert(myString.toUpperCase()); alert(myString['toLowerCase']());

Like properties you can set instance methods for a particular objects
myString.sayWhat = function() {alert('What?')}; myString.sayWhat();

CSE 130

Programming Language Principles & Paradigms

Lecture #

Enumerating Objects
The for-in loop can be used to enumerate object properties (and sometimes methods)
for (prop in window.navigator) document.write('window.navigator["' + prop + '"] = ' + window.navigator[prop] + '<br />');

Some browsers may not enumerate methods and some objects particularly built-ins are not enumeratable just instances are
var myString = new String('hi'); myString.foo = true; for (prop in myString) document.write('myString["' + prop + '"] = ' + myString[prop] + '<br />'); for (prop in String) document.write('String["' + prop + '"] = ' + myString[prop] + '<br />'); // nothing

CSE 130

Programming Language Principles & Paradigms

Lecture #

The with() statement


Using with you can shorthand object references
with (document) { write('hi '); write('there'); }

The with statement adds the object to the front of the scope chain during the block of execution trying the used values/methods there first Note the with statement may reduce/increase performance due to less/extra scope resolution

CSE 130

Programming Language Principles & Paradigms

Lecture #

Objects as Reference Types


All JavaScript types can be categorized as primitive or reference types Reference types include Objects, Arrays, and Functions and since they can be large they do not contain the actual data but references to the place in memory that holds the data
var city = new Object(); city.name = 'San Diego'; city2 = city; city2.name = 'Los Angeles'; alert("city.name = " + city.name); // shows Los Angeles

CSE 130

Programming Language Principles & Paradigms

Lecture #

Reference Types Contd.


Given the way reference types work you will find them useful with functions which usually pass parameters by value in the case of primitive types
function fiddle(x) { // x can be changed if reference not if primitive }

10

CSE 130

Programming Language Principles & Paradigms

Lecture #

Comparing Objects
When comparing primitive types things work as expected, but with objects which are reference types you are comparing a reference to data not the data itself so the comparison may fail
var str1 = "abc"; var str2 = "abc"; alert(str1 == str2); // true str1 = new String("abc"); str2 = new String("abc"); alert(str1 == str2); // false alert(str1.valueOf() == str2.valueOf() ); // true

CSE 130

Programming Language Principles & Paradigms

Lecture #

User-Defined Object Intro


Generic objects are used to create user-defined data types
var robot = new Object(); robot.name = "Zephyr"; robot.model = "Guard"; robot.hasJetPack = true; alert(robot.name + " " + robot.model); robot.attack = function () { alert('Zap!'); }; robot.attack();

CSE 130

Programming Language Principles & Paradigms

Lecture #

Object Literals
Object literals have been supported since JS 1.2 and are defined as { name1 : value1, name-n: value-n;}
var robot2 = { name: "Arnold", model: "Terminator", hasJetPack: false, attack: function() {alert('Hasta la vista!');} }; alert(robot2.name + " " + robot2.model); robot2.attack();

11

CSE 130

Programming Language Principles & Paradigms

Lecture #

Object Literals Contd.


You can build quite large objects this way if you like var jetpack = true; var robot3 = { name: null, hasJetpack: jetpack, model: "Protocol Droid", attack: function() { alert("Ahhhh!"); }, sidekick: { name: "Spot", model: "Dog", hasJetpack: false, attack: function() { alert("CHOMP!"); } } }; robot3.name = "C-3PO"; alert(robot3.name + " " + robot3.model); robot3.sidekick.attack();

CSE 130

Programming Language Principles & Paradigms

Lecture #

Objects as Associative Arrays


You can also use an associate array style for object access (or you could say associative arrays are just objects?)
var customers = new Object(); customers["John Doe"] = "123 Main St SD, CA"; alert(customers["John Doe"]);

The advantage here is that you can use property names not known until run time
customerName = prompt("Enter name", ""); customerAddress = prompt("Enter address", ""); customers[customerName] = customerAddress; alert(customerName); alert(customers[customerName]);

CSE 130

Programming Language Principles & Paradigms

Lecture #

Constructors
Constructors are special functions that prepare new instances of an object for use
A constructor contains an object prototype that defines the code and data that each object instance has by default
function Robot() { } // caps just convention var guard = new Robot(); function Robot(needsToFly) { if (needsToFly == true) this.hasJetpack = true; else this.hasJetpack = false; } // create a Robot with hasJetpack == true var guard = new Robot(true); // create a Robot with hasJetpack == false var sidekick = new Robot();

12

CSE 130

Programming Language Principles & Paradigms

Lecture #

Prototypes
Every object has a prototype property that gives it its structure. The prototype is a reference to an Object describing the code and data that all objects of that type have in common
Robot.prototype.hasJetpack = false; Robot.prototype.doAction = function() { function Robot(flying) { if (flying == true) this.hasJetpack = true; } var guard = new Robot(true); var canFly = guard.hasJetpack; guard.doAction(); alert(Watch it!"); };

CSE 130

Programming Language Principles & Paradigms

Lecture #

Using Prototypes
Prototypes are of course shared so you can do some interesting things
String.prototype.getThirdChar = function() { return this.charAt(2); } Now you can invoke this method as you would any other built-in String method: var c = "Example".getThirdChar(); // c set to 'a'

Sometimes you dont even need to do prototypes though esp. if you just want to improve some built-in object instances
document.writeln = function(s) { document.write(s + "<br />\n") }; document.writeln('he there'); document.writeln('thomas powell');

CSE 130

Programming Language Principles & Paradigms

Lecture #

Inheritance via the Prototype Chain


Inheritance in JavaScript is achieved through prototypes. Derive a new object type from a type that already exists inheriting all the properties of their own type in addition to any properties embodied in their parent.
function UltraRobot(extraFeature) { if (extraFeature) this.feature = extraFeature; } UltraRobot.prototype = new Robot(); UltraRobot.prototype.feature = "Radar"; var guard = new UltraRobot("Performs Calculus"); var feature = guard.feature; var canFly = guard.hasJetpack; guard.doAction();

13

CSE 130

Programming Language Principles & Paradigms

Lecture #

Common Properties and Methods


Property prototype Description Reference to the object from which it inherits non-instance properties

constructor

Reference to the function object that served as this objects constructor

toString()

Converts the object into a string (object-dependent behavior)

toLocaleString()

Converts the object into a localized string (object-dependent behavior)

valueOf()

Converts the object into an appropriate primitive type, usually a number

hasOwnProperty(prop)

Returns true if the object has an instance property named prop, false otherwise

isPrototypeOf(obj)

Returns true if the object serves as the prototype of the object obj

propertyIsEnumerable(prop)

Returns true if the property give in the string prop will be enumerated in a for/in loop

CSE 130

Programming Language Principles & Paradigms

Lecture #

OOP Use in JavaScript


JavaScript does support the four apsects of OOP
Abstraction Encapsulation Inheritance Polymorphism

However, the lack of OOP programming is apparent.


Could it be because of the types of applications built? Could it be the type of user writing code? Does it mean a language has to be used only one way in order to be useful? We leave these questions for you to answer yourself depending on the project you are working on

CSE 130

Programming Language Principles & Paradigms

Lecture #

Two Object Models?


An object model defines the interface to the various aspects of the browser and document that can be manipulated by JavaScript. In JavaScript, two primary object models are employed
1. a browser object model (BOM)
The BOM provides access to the various characteristics of a browser such as the browser window itself, the screen characteristics, the browser history and so on. The DOM on the other hand provides access to the contents of the browser window, namely the document including the various HTML elements ranging from anchors to images as well as any text that may be enclosed by such elements.

2. document object model (DOM).

14

CSE 130

Programming Language Principles & Paradigms

Lecture #

The Ugly Truth


Unfortunately, the division between the DOM and the BOM at times is somewhat fuzzy and the exact document manipulation capabilities of a particular browsers implementation of JavaScript vary significantly.

CSE 130

Programming Language Principles & Paradigms

Lecture #

The Big Picture


Looking at the "big picture" of all various aspects of JavaScript including its object models. We see four primary pieces:
1. The core JavaScript language (e.g. data types, operators, statements, etc.) 2. The core objects primarily related to data types (e.g. Date, String, Math, etc.) 3. The browser objects (e.g. Window, Navigator, Location, etc.) 4. The document objects (e.g. Document, Form, Image, etc.)

CSE 130

Programming Language Principles & Paradigms

Lecture #

15

CSE 130

Programming Language Principles & Paradigms

Lecture #

Four Models
By studying the history of JavaScript we can bring some order to the chaos of competing object models. There have been four distinct object models used in JavaScript including:
1. 2. 3. Traditional JavaScript Object Model (NS 2 & IE 3) Extended Traditional JavaScript Object Model (NS 3) Dynamic HTML Flavored Object Models 1. a. IE 4 2. b. NS 4 Traditional Browser Object Model + Standard DOM (NS6 & Explorer 5)

4.

CSE 130

Programming Language Principles & Paradigms

Lecture #

Traditional Object Model

CSE 130

Programming Language Principles & Paradigms

Lecture #

Overview of Core Objects


Object Window Document Description The object that relates to the current browser window. An object that contains the various HTML elements and text fragments that make up a document. In the traditional JavaScript object model, the Document object relates roughly the HTML <body> tag. An array of the frames in the Window contains any. Each frame in turn references another Window object that may also contain more frames. An object that contains the current windows history list, namely the collection of the various URLs visited by the user recently. Contains the current location of the document being viewed in the form of a URL and its constituent pieces. An object that describes the basic characteristics of the browser, notably its type and version.

Frames[ ]

History Location Navigator

16

CSE 130

Programming Language Principles & Paradigms

Lecture #

Document Object
The Document object provides access to page elements such as anchors, form fields, and links as well as page properties such as background and text color. Consider
document.alinkColor, document.bgColor, document.fgColor, document.URL document.forms[ ], document.links[ ], document.anchors[ ]

We have also used the methods of the Document object quite a bit
document.write( ) , document.writeln( ), document.open( ), document.close( )

CSE 130

Programming Language Principles & Paradigms

Lecture #

Object Access by Document Position


HTML elements exposed via JavaScript are often placed in arrays or collections. The order of insertion into the array is based upon the position in the document. For example, the first <form> tag would be in document.forms[0], the second in document.forms[1] and so on. Within the form we find a collection of elements[ ] with the first <input>, <select> or other form field in document.forms[0].elements[0] and so on. As arrays we can use the length property to see how many items are in the page. The downside of access by position is that if the tag moves the script may break

CSE 130

Programming Language Principles & Paradigms

Lecture #

Object Access by Name


When a tag is named via the name attribute (HTML 4.0 - <a>, <img>, embedded objects, form elements, and frames) or by id attribute (pretty much every tag) it should be scriptable. Given <form id=myform name=myform> <input type=text name=username id=username> </form> we can access the form at window.document.myform and the first field as window.document.myform.username

17

CSE 130

Programming Language Principles & Paradigms

Lecture #

Object Access by Associative Array The collection of HTML objects are stored associatively in the arrays. Given the form named myform we might access it using
window.document.forms[myform]

In Internet Explorer we can use the item( ) method like so


window.document.forms.item(myform)

CSE 130

Programming Language Principles & Paradigms

Lecture #

Event Models
JavaScript reacts to user actions through event handlers (code associated with a particular event or object and event in the page) Common events include Click, MouseOver, MouseOut, etc. Events can be registered through HTML event handlers like onclick or via JavaScript directly
<input type=button value=press onclick=alert(hi)> document.onload = new Function(alert(hi));

Well see events primarily with links, form items and mouse movement

CSE 130

Programming Language Principles & Paradigms

Lecture #

All Together
Once document objects are accessed either by user event or script event we can then modify the various properties of the elements. The following examples on the next slides show reading and writing of form fields as a demonstration of this.

18

CSE 130

Programming Language Principles & Paradigms

Lecture #

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Meet and Greet</title> <script language="JavaScript" type="text/javascript"> <!-function sayHello() { var theirname=document.myform.username.value; if (theirname !="") alert("Hello "+theirname+"!"); else alert("Don't be shy."); } // --> </script></head><body> <form name="myform" id="myform"> <b>What's your name?</b> <input type="text" name="username" id="username" size="20"><br><br> <input type="button" value="Greet" onclick="sayHello()"> </form> </body> </html>

CSE 130

Programming Language Principles & Paradigms

Lecture #

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html><head><title>Meet and Greet 2</title> <script language="JavaScript" type="text/javascript"> <!-function sayHello() { var theirname = document.myform.username.value; if (theirname != "") document.myform.response.value="Hello "+theirname+"!"; else document.myform.response.value="Don't be shy."; } // --> </script></head><body> <form name="myform" id="myform"> <b>What's your name?</b> <input type="text" name="username" id="username" size="20"> <br><br> <b>Greeting:</b> <input type="text" name="response" id="response" size="40"> <br><br> <input type="button" value="Greet" onclick="sayHello()"> </form></body></html>

CSE 130

Programming Language Principles & Paradigms

Lecture #

The Object Models


The next few slides present the various object models supported pre-standard DOM. In JavaScript 1 we focus primarily on the Netscape 3 DOM with some introduction to the nonstandard DHTML object models.

19

CSE 130

Programming Language Principles & Paradigms

Lecture #

Specific Object Models: Netscape 3

CSE 130

Programming Language Principles & Paradigms

Lecture #

Specific Object Models: Netscape 4

CSE 130

Programming Language Principles & Paradigms

Lecture #

Specific Object Models: Internet Explorer 3

20

CSE 130

Programming Language Principles & Paradigms

Lecture #

Specific Object Models: Internet Explorer 4

CSE 130

Programming Language Principles & Paradigms

Lecture #

The Cross Browser Nightmare


The problem we face with JavaScript is that each object model is different Somehow we either have to find a common ground (traditional model), use object detection, use browser detection, pick a particular object model like IE and stick with it or just hope the standards work out Well see with the rise of the Document Object Model (DOM) that someday maybe only certain BOM features will be non-standard and all browsers will have the same ability to manipulate page content.

CSE 130

Programming Language Principles & Paradigms

Lecture #

Summary
This chapter introduces how to access browser and document objects in the traditional manner
By name and by document location

All the various object models were presented from NS 2 to modern day browsers The problem of cross browser compatibility starts to become apparent when you compare the models

21

CSE 130

Programming Language Principles & Paradigms

Lecture #

The Standard Document Object Model

CSE 130

Programming Language Principles & Paradigms

Lecture #

DOM Flavors
The Document Object Model or DOM is a standard that maps HTML and XML documents into objects for manipulation by scripting languages such as JavaScript The DOM comes in the following flavors:
DOM Level 0 roughly equivalent to NS3s object model. Often called traditional or classic object model DOM Level 1 Maps all the HTML elements and provides generic node manipulation features via the document object. DOM Level 2 Maps all CSS properties Note: The later DOM levels also support the earlier objects so classic scripts should work under DOM

CSE 130

Programming Language Principles & Paradigms

Lecture #

DOM Flavors Contd.


Another breakdown of the DOM is
DOM Core core features for node manipulation (create, delete, movement, etc.) DOM HTML bindings to HTML tags (HTMLParagraph, etc.) DOM CSS bindings to CSS properties DOM Events event handling support DOM XML bindings to deal with user defined XML languages

Todays modern browsers like IE 5+ and NS 6+ support DOM Core, DOM HTML, and a good portion of DOM CSS. However, DOM events and DOM XML are not consistently supported

22

CSE 130

Programming Language Principles & Paradigms

Lecture #

Document Trees
The key to understanding the DOM is how an HTML document is modeled as a tree (Didnt we just talk about parse trees!). Consider
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head><title>DOM Test</title></head> <body> <h1>DOM Test Heading</h1> <hr> <!-- Just a comment --> <p>A paragraph of <em>text</em> is just an example</p> <ul> <li><a href="http://www.yahoo.com">Yahoo!</a></li> </ul> </body> </html>

CSE 130

Programming Language Principles & Paradigms

Lecture #

Modeled Document Tree

CSE 130

Programming Language Principles & Paradigms

Lecture #

Looking at the Tree


The tree structure follows the structured nature of HTML. <html> tags encloses <head> and <body>. <head> encloses <title> and so on. Each of the items in the tree is called generically a node Notice that are different types of nodes corresponding to HTML elements, text strings, and even comments. The types of nodes relevant to most JavaScript programmers is shown on the next slide.

23

CSE 130

Programming Language Principles & Paradigms

Lecture #

Node Types
N ode T ype N um b er 1 2 E le m e n t A ttrib u te A n H TM L or X M L e le m e n t. A n a ttr ib u te fo r an H TM L or X M L e le m e n t. A fragm en t o f te x t th a t w o u ld b e e n c lo s e d b y an H TM L or X M L e le m e n t An HTM L com m ent T h e ro o t docum ent o b je c t, n a m e ly th e to p e le m e n t in th e p a r s e tre e A docum ent typ e d e fin itio n < p > < /p > a lig n = c e n te r T ype D e s c r ip tio n E x a m p le

T ext

T h is is a te x t f ra g m e n t!

8 9

C om m ent D ocum ent

< !- - T h is is a c o m m e n t - - > < h tm l>

10

D o c u m e n tT y p e

< !D O C T Y P E H T M L P U B L IC " //W 3 C //D T D H T M L 4 .0 1 T r a n s itio n a l//E N " " h ttp ://w w w .w 3 .o r g /T R /h tm l4 /lo o s e .d td " >

CSE 130

Programming Language Principles & Paradigms

Lecture #

Node Relationships
Look at the tree for
<p>A paragraph of <em>text</em> is just an example</p>

Notice that the <p> tag has three direct children and one grandchild Also make sure you understand the sibling and parent relationships. The DOM relies on them

CSE 130

Programming Language Principles & Paradigms

Lecture #

Node Relationships Contd.

24

CSE 130

Programming Language Principles & Paradigms

Lecture #

Accessing Nodes
The easiest way to access nodes in a document tree is via the getElementById( ) method for the Document object. In order to use the method we need to name our tags using the HTML 4 core attribute id like so <p id="p1" align="center">A paragraph of <em>text</em> is just an example</p>

CSE 130

Programming Language Principles & Paradigms

Lecture #

Accessing Nodes Contd.


Using document.getElementById(p1) we are returned an DOM Element object that corresponds to the appropriate node in the tree.
var currentElement = document.getElementById('p1'); var msg = "nodeName: "+currentElement.nodeName+"\n"; msg += "nodeType: "+currentElement.nodeType+"\n"; msg += "nodeValue: "+currentElement.nodeValue+"\n"; alert(msg);

CSE 130

Programming Language Principles & Paradigms

Lecture #

Accessing Nodes Contd.


Notice the node value to be 1 (an element), the type P corresponding to the HTML <p> tag, and the nodeValue is null. The reason for the null value is that you have to look at a text node to see the text within the parent tag. We now need to learn how to move around the tree. Fortunately there are some generic node properties that make this very easy as summarized on the next slide.

25

CSE 130

Programming Language Principles & Paradigms

Lecture #

DOM Node Properties


D O M N o d e P r o p e r tie s nodeN am e n o d e V a lu e n o d e T yp e p a re n tN o d e c h ild N o d e s firs tC h ild la s tC h ild p re v io u s S ib lin g D e s c r ip tio n C o n ta in s th e n a m e o f th e n o d e C o n ta in s th e v a lu e w ith in th e n o d e , g e n e ra lly o n ly a p p lic a b le to te x t n o d e s H o ld s a n u m b e r c o rre s p o n d in g to th e ty p e o f n o d e , a s g iv e n in T a b le 1 0 -1 A re fe re n c e to th e p a re n t n o d e o f th e c u rre n t o b je c t, if o n e e x is ts A c c e s s to lis t o f c h ild n o d e s R e fe re n c e to th e firs t c h ild n o d e o f th e e le m e n t, if o n e e x is ts P o in ts to th e la s t c h ild n o d e o f th e e le m e n t, if o n e e x is ts R e fe re n c e to th e p re v io u s s ib lin g o f th e n o d e ; fo r e x a m p le , if its p a re n t n o d e h a s m u ltip le c h ild re n R e fe re n c e to th e n e x t s ib lin g o f th e n o d e ; fo r e x a m p le , if its p a re n t n o d e h a s m u ltip le c h ild re n T h e lis t o f th e a ttrib u te s fo r th e e le m e n t P o in ts to th e H T M L D o c u m e n t o b je c t in w h ic h th e e le m e n t is c o n ta in e d

n e x tS ib lin g

a ttrib u te s o w n e rD o c u m e n t

CSE 130

Programming Language Principles & Paradigms

Lecture #

Basic Movement
Using the common node properties you should be able to move around a tree that you know the structure of
var currentElement = document.getElementById(p1); currentElement = currentElement.firstChild; currentElement = currentElement.nextSibling; currentElement = currentElement.parentNode;

This simple script would end up right were it started from assuming that the starting node had at least two children.

CSE 130

Programming Language Principles & Paradigms

Lecture #

Basic Movement Contd.


We need to be careful though when we dont know the tree structure ahead of time Use simple conditionals to protect yourself from moving off tree
if (current.hasChildNodes()) current = current.firstChild; if (current.parentNode) current = current.parentNode;

You should be able to easily write a safe tree traversal system once you know the core properties and how to do if statements

26

CSE 130

Programming Language Principles & Paradigms

Lecture #

getElementsByName
Related to getElementById( ) is the DOM method getElementsByName( ) which deals with HTML elements identifed by the name attribute including: <form>, <input>, <select>, <textarea>, <img>, <a>, <area>, and <frame> Elements using name actually didnt have to have globally unique names thus the DOM method getElementsByName( ) returns a list of nodes with the passed name as shown here looking for something called mytag
tagList = document.getElementsByName('myTag'); for (var i = 0; i < tagList.length; i++) alert(tagList[i].nodeName);

CSE 130

Programming Language Principles & Paradigms

Lecture #

Traditional JavaScript Collections


For backwards compatibility the DOM supports some object collections such as document.forms[ ] , document.images[ ] and so forth which were commonly supported amongst JavaScript aware browsers.
Collection document.anchors[ ] document.applets[ ] document.forms[ ] document.images[ ] document.links[ ] Description A collection of all the anchors in a page specified by <a name=> </a> A collection of all the Java applets in a page A collection of all the <form> tags in a page A collection of all images in the page defined by <img> tags A collection of all links in the page defined by <a href=> </a>

CSE 130

Programming Language Principles & Paradigms

Lecture #

Generalized Element Collections


Under the DOM you can create an arbitrary collection of elements using getElementsByTagName( )
allparagraphs = document.getElementsByTagName(p);

You can use many of these methods on nodes themselves to find the elements within a particular element
allparagraphsinbody = document.body.getElementsByTagName(p); para1=document.getElementById(p1); emElements = para1.getElementsByTagName(em);

27

CSE 130

Programming Language Principles & Paradigms

Lecture #

Common Tree Starting Points


Rather than using a built-in collection or a named starting point you may simply want to start at a well know common tree position such as : document.documentElement
should be the <html> tag

document.body
<body> tag

document.doctype
should be the <!doctype> statement but may not be and has limited value

CSE 130

Programming Language Principles & Paradigms

Lecture #

Creating Nodes
You can create nodes and then insert them into the document tree
newNode = document.createElement(p);

Of course you may have to then create text nodes to put inside of elements
newText = document.createTextNode(Hello there);

Then we will attach things together and attachto the document


newNode.appendChild(newText); document.body.appendChild(newNode);

CSE 130

Programming Language Principles & Paradigms

Lecture #

Create Node Methods


Method createAttribute(name); Description Example myAlign = document.createAttribute(align); Creates an attribute for an element specified by the string name. Rarely used with existing HTML elements since they have predefined attribute names that can be manipulated directly. createComment(string); Creates an HTML/XML text comment of the form <!-- string --> where string is the comment content. createElement(tagName) Creates an element of the type specified by the string parameter tagName createTextNode(string) Creates a text node containing string.

myComment = document.createComment(Just a comment); myHeading = document.createElement(h1); newText = document.createTextNode(Some new text);

28

CSE 130

Programming Language Principles & Paradigms

Lecture #

Insert and Append Methods


The two methods for node attaching are insertBefore(newChild, referenceChild) and appendChild(newChild) These methods run on a node object, for example
newText = document.createTextNode(Hi!); currentElement = document.body; insertPt = document.getElementById(p1); currentElement.insertBefore(insertPt,newText);

CSE 130

Programming Language Principles & Paradigms

Lecture #

Copying Nodes
Use the cloneNode( ) method to make a copy of a particular node. The method take a Boolean argument which indicates if the children of the node should be cloned (a deep clone) or just the node itself var current = document.getElementById(p1); newNode = current.cloneNode(); newSubTree = current.cloneNode(true);

CSE 130

Programming Language Principles & Paradigms

Lecture #

Deleting Nodes
The Node objects removeChild(child) method is useful to delete a node out of the tree. You need to run this node on the parent of the object you are interested in deleting var current = getElementById(p1); currentParent = current.parentNode; currentParent.removeChild(current); Note: The removeChild( ) method does return the node object removed.

29

CSE 130

Programming Language Principles & Paradigms

Lecture #

Replacing Nodes
You can also replace a node using replaceChild(newchild, oldChild) The replaceChildChild( ) method will destroy the contents of the node replace and does not side effect the old value

CSE 130

Programming Language Principles & Paradigms

Lecture #

Modifying Nodes
You cant modify an element directly but you can modify its contents particularly text nodes. Given Use
<p id=p1>This is a test</p> textNode = document.getElementById(p1).firstChild; textNode.data = Ive been changed!;

then set the textNodes data property

There are a variety of DOM methods like appendData( ), deleteData( ), insertData( ), replaceData( ), splitText( ), and substringData( ) that can be used, but since the data value is just a string you might want to resort to commonly understood String object methods.

CSE 130

Programming Language Principles & Paradigms

Lecture #

Modifying Attributes
Attributes can be manipulated by DOM methods like getAttribute(name), setAttribute(attributename, attributevalue) and removeAttribute(attributeName) that work off a particular Node object. You can also check for the existence of attributes using the hasAttributes( ) method. Most people do not use these DOM methods but directly modify the attributes of the tag like so <p id=p1 align=left>This is a test</p> You would use current = document.getElementById(p1); current.align = right;

30

CSE 130

Programming Language Principles & Paradigms

Lecture #

The DOM and HTML


What you should begin to recognize now is the key to the DOM in most Web pages is understanding HTML The various properties of a node correspond directly to its HTML attributes. For example given a paragraph tag <p> it corresponds to an HTMLParagraphElement with the following properties align, id, className, title, lang, and dir. Notice the mapping from HTML attributes to object properties is nearly one-to-one except for some situations like the class attribute which would be a reserved word and thus is renamed className under the DOM. Two word attributes like tabindex are represented in the DOM in typical programming camel back form (e.g. tabIndex)

CSE 130

Programming Language Principles & Paradigms

Lecture #

The DOM and HTML


The ramification of this relationship between HTML and JavaScript via the DOM is that the language can now manipulate any arbitrary HTML element in anyway, but it does require a well formed document otherwise the results can be somewhat unpredictable Suddenly, knowing how to do HTML properly actually matters. Even WYSIWYG editors will have to modified to ensure 100% validatable markup to ensure correct JavaScript operation The intersection with CSS is very similar and covered under DOM Level 2

CSE 130

Programming Language Principles & Paradigms

Lecture #

The DOM and CSS


The style attribute for an HTML element allows style sheets properties to be set inline. The DOM allows access to this attributes value, for example given
<p id=p1 style=color: red>Test</p>

then
theElement = document.getElementById(p1); theElement.style.color = green;

What we see is like HTML the various CSS properties map to DOM names directly, so font-size becomes fontSize, background-color becomes backgroundColor, and so on. There are only one or two exceptions to this conversion.

31

CSE 130

Programming Language Principles & Paradigms

Lecture #

The DOM and CSS Contd.


We can manipulate the className and id properties of an element as well to effect a style sheet change We can access the complete style sheet using the document.styleSheets[ ] collection and then looking at the cssRules[ ] collection within each <style> tag. You can addRule( ), removeRule( ) and insertRule( ) on an given style sheet as well as change the various properties and values. Be careful this aspect of the DOM Level 2 is poorly implemented so far in browsers

CSE 130

Programming Language Principles & Paradigms

Lecture #

DOM Conclusions
The DOM represents the possibility for easier crossbrowser scripting, but it also requires mastery of CSS and HTML to be used properly Some aspects of the BOM are actually easier to use than the DOM
Consider creating nodes or manipulating text contents, some programmers find using properties like innerHTML, innerText, outerText, and outerHTML to be far easier than making nodes one by one

A great deal of legacy code using BOM objects like IEs document.all[ ] style exist and would have to be ported. This will take time!

CSE 130

Programming Language Principles & Paradigms

Lecture #

Summary
JavaScript isnt a toy language
It is very object focused but not in the class manner that is familiar to Java programmers but instead using prototypes The way JS is implemented you dont have to program OOP style if you dont want to Interestingly related as well see even more later to Functional languages like SELF

It has many unknown aspects to most coders


High order programming, reflective capabilities, prototypes, relationship to window, reference types, meaning of var, local functions, anonymous functions, etc.

JS gets nasty when you intersect with the various browser and document object models It is still maturing
http://www.mozilla.org/js/language/ICFP-Keynote.ppt

It is getting interesting because Ajax is taking off

32

S-ar putea să vă placă și