+ All Categories
Home > Documents > JavaScriJavaScript Overview.

JavaScriJavaScript Overview.

Date post: 04-Jun-2018
Category:
Upload: rtarak
View: 234 times
Download: 0 times
Share this document with a friend

of 32

Transcript
  • 8/13/2019 JavaScriJavaScript Overview.

    1/32

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    JavaScript Overview

    Part II

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Function Basics

    Functions are used to create code fragments that can beused over and over again. Hopefully, these are abstractreusable 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 mayalso be empty

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Function Example 1

    Simple function with no parameters

    f uncti on sayHel l o(){

    al er t ( "Hel l o there") ;}

    sayHell o(); / / i nvoke the functi on

    Note: You generally will be unable to call a function before it isdefined. This suggests that you should define your functions in the of your (X)HTML document. However, in some JavaScriptimplementations you can forward reference with the same block.

  • 8/13/2019 JavaScriJavaScript Overview.

    2/32

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Function Example 2: Parameters

    f unct i on sayHel l o(name){

    i f ( name != " ")

    al ert ( "Hel l o there "+name) ;el seal ert ( "Don t be shy. ") ;

    }

    / * Make some cal l s */sayHel l o( "Geor ge") ;

    sayHel l o();

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Example 3: Multiple Parameters & Return

    f unct i on addThree(ar g1, arg2, ar g3){return (arg1 + arg2 + arg3);

    }

    var x = 5, y = 7, resul t ;resul t = addThree( x,y, 11) ;al ert ( resul t ) ;

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Example 4: Multiple Returns

    f unct i on myMax(ar g1, arg2){

    i f ( arg1 >= arg2)r eturn ar g1

    el se

    r eturn arg2;}

    Note: Functions always return some value whether or nota r e t u rn is explicitly provided. Usually it is a value ofundef ined .

  • 8/13/2019 JavaScriJavaScript Overview.

    3/32

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Parameter Passing

    Primitive Data types are passed by value, in other words acopy of the data is made and given to the function

    f uncti on fi ddl e(arg1){

    arg1 = 10;

    document. wri t e( "I n f i ddl e arg1 = "+ar g1+"
    ") ;}

    var x = 5;

    document. wr i t e( "Before funct i on cal l x = "+x+"
    ") ;f i ddl e(x) ;

    document. wr i t e( "Aft er funct i on cal l x = "+x+"
    ") ;

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Parameter Passing 2

    Composite types are passed by reference in JS

    f uncti on f i ddl e(arg1){

    arg1[0] = "changed";document. wr i t e( "I n f i ddl e arg1 = "+ar g1+"
    ") ;

    }

    var x = [ "f i r st ", "second", "t hi r d"] ;document. wr i t e( "Before funct i on cal l x = "+x+"
    ") ;f i ddl e(x);document. wr i t e( "Af t er func t ion cal l x = "+x+"
    ") ;

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Global and Local Variables

    Aglobal 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 varstatements are local

  • 8/13/2019 JavaScriJavaScript Overview.

    4/32

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Global and Local Example

    // Define x globally

    varx = 5;

    function myFunction()

    {

    document.write("Entering function
    x="+x+
    ");document.write("Changing x
    ");

    x = 7;

    document.write("x="+x+"
    Leaving function
    ");

    }

    document.write("Starting Script
    ");

    document.write("x="+x+"
    ");

    myFunction();

    document.write("Returning from function
    ");

    document.write("x="+x+"
    ");

    document.write("Ending Script");

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Local Variable Example

    f uncti on myFuncti on( )

    {

    var y=5; / / defi ne a l ocal vari abl e

    document. wr i t e(" Wi t hi n f unct i on y="+y) ;

    }

    myFunct i on() ;

    document. wri te( "Aft er f uncti on y="+y);

    Note: This example will throw an error, but thats the point. You could usean if statement to avoid problems like

    i f (wi ndow. y)document. wri t e("Af ter f uncti on y="+y);

    el sedocument. wri t e("Y i s undef i ned");

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Mask Out

    Be careful when you have local and global variables ofthe same name, you may get an undesirable effect calledmask out.

    var x =" As a gl obal I ama stri ng";

    f uncti on maskDemo( ){

    var x = 5;

    document. wri t e(" I n f unct i on maskDemo x="+x+"
    ") ;

    }

    document. wri te( "Before f uncti on cal l x="+x+"
    ") ;

    maskDemo( ) ;

    document. wri te( "Aft er f uncti on cal l x="+x+"
    ") ;

  • 8/13/2019 JavaScriJavaScript Overview.

    5/32

  • 8/13/2019 JavaScriJavaScript Overview.

    6/32

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Useful Function Features

    As objects you can reference the length of functions,thus find out the number of arguments

    f unct i on myFunct i on( arg1, arg2, arg3){

    / / do somethi ng}al ert ( "Number of par ameters f or myFunct i on= "+myFuncti on. l engt h);

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Arguments and Length

    You can examine not just defined arguments but actual

    passed parameters

    f uncti on myFuncti on( )

    {

    document. wr i t e(" Number of parameter s def i ned ="+myFuncti on. l ength+"
    ") ;

    document. wr i t e( "Number of par amet er s passed ="+myFunct i on.ar guments. l ength+"
    ")

    f or ( i =0;i

  • 8/13/2019 JavaScriJavaScript Overview.

    7/32

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Literal and Anonymous Functions

    f uncti on si mpl eRobot( robotName){

    t hi s. name = r obotName;

    thi s. sayHi = f uncti on () { alert (' Hi my name is' +thi s. name); };this . sayBye = funct i on () { alert( ' Bye! ' ) ; };

    thi s. sayAnything = functi on (msg) { al ert( thi s. name+'says ' +msg) ; };}

    fr ed. sayHi () ;fr ed. sayAnythi ng(" I don' t knowwhat to say") ;

    f red.sayBye( );

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Recursive Functions

    JS supports recursive functions that call themselves

    Factorial n! = n*(n-1)*(n-2) * 1funct i on f actor i al (n)

    {i f (n == 0)

    ret urn 1;else

    return n* factori al( n 1);}

    al er t ( f actor ia l (5 ) ) ;

    Demo this with negative value in Internet Explorer

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    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 noviceJavaScript programmers but become quite important asyou build larger and larger Web applications

  • 8/13/2019 JavaScriJavaScript Overview.

    8/32

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Object Creation

    Use the new( ) operator along with the appropriateconstrictor functionvar c i t y = new St r i ng( ) ;

    var ci ty = newStri ng(San Di ego);var ci ty2 = San Di ego;al ert ( typeof c i t y) ;al ert ( typeof c i t y2);

    Of course we will often be making our own objectsvar c i t y = new Obj ect () ;ci ty. name = San Di ego;c i ty . sunny = t rue;

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Object Destruction

    We dont have to do much as within browserimplementation of JavaScript garbage collection cleansup unused object references we may havevar mySt r i ng = new St r i ng( Larry F ine ) ;

    myStr i ng = new Stri ng( Moe Howard );

    / / Larr y Fi ne stri ng eventuall y garbage coll ected

    Better to hint to the browser you are done with memorythough.var c i t y = new Obj ect () ;

    cit y = nul l ; / / hi nt to garbage col l ector

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Properties

    Apropertyis named data contained in an objectvar mySt r i ng = new Str i ng( ' hel l o there' ) ;

    alert (myStr i ng.l ength);

    Properties that are not set return undefined

    Instance properties can be added to a particular object and deletedas wellvar mySt r i ng = new Str i ng( ' hi ' ) ;

    myStr i ng. si mpl eExample = tr ue;

    al ert ( mySt ri ng. si mpl eExampl e);

    del ete myStr i ng. si mpl eExampl e;

    al ert (mySt ri ng. si mpl eExampl e); / / undefi ned

  • 8/13/2019 JavaScriJavaScript Overview.

    9/32

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Array Style Property Access

    You can also use [ ] to access a property of anobject by namevar mySt r i ng = new St r i ng( ' hi ' ) ;

    alert( myStr i ng[' l ength'] );

    myStr i ng[ ' si mpl eExampl e' ] =tr ue;

    alert (myStr i ng[' si mpleExample' ]) ;

    del ete(mySt ri ng[ ' si mpl eExampl e' ]) ;

    alert (myStr i ng[' si mpleExample' ]) ;

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

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Methods

    Object properties that are functions are called methods

    You can use the standard . operator as well as the array syntax toaccess a method but add the ( ) to invoke the methodvar mySt r i ng = new St r i ng("Hi there") ;

    al ert ( myStr i ng. toUpperCase() ) ;

    alert (myStr i ng[' toLowerCase' ]( )) ;

    Like properties you can set instance methods for a particularobjects myStri ng. sayWhat = f unct i on() {alert( ' What?' )};

    myStr i ng. sayWhat( );

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Enumerating Objects

    The for-in loop can be used to enumerate object properties (and sometimesmethods)f or ( prop i n wi ndow. navi gator )document. wri te(' wi ndow. navi gator[ "' + prop + ' "] = ' +

    wi ndow. navi gator[prop] + '
    ' );

    Some browsers may not enumerate methods and some objects particularly

    built-ins are not enumeratable just instances arevar mySt r i ng = new St r i ng( ' hi ' ) ;myStr i ng. foo = true;f or ( prop i n myStr i ng)

    document. wri te(' myStr i ng["' + prop + ' "] = ' +myStr i ng[prop] + '
    ' );f or (prop i n Stri ng)

    document. wri te(' Stri ng["' + prop +' "] = ' + myStri ng[prop] +'
    ' ) ; / / noth ing

  • 8/13/2019 JavaScriJavaScript Overview.

    10/32

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    The with() statement

    Using with you can shorthand object referenceswi t h (document)

    {

    wr i t e( ' hi ' ) ;

    wr i te ( ' 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 # 6

    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 datavar c i t y = new Obj ect () ;

    ci ty. name = ' San Di ego';

    c i t y2 = ci t y;

    ci ty2. name = ' Los Angel es' ;

    alert (" ci ty. name = " + ci ty. name); / / shows Los Angeles

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    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 typesfunct i on f i ddl e(x)

    {

    / / x can be changed i f reference not i f pri mi ti ve}

  • 8/13/2019 JavaScriJavaScript Overview.

    11/32

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Comparing Objects

    When comparing primitive types things work asexpected, but with objects which are reference typesyou are comparing a reference to data not the data

    itself so the comparison may failvar s t r1 = "abc";var s t r2 = "abc";al er t ( s t r1 == s t r2) ; / / t rue

    str 1 = new Stri ng("abc");str 2 = new Stri ng("abc");al er t ( s t r1 == s t r2) ; / / f a lse

    al ert (s tr 1. val ueOf( ) == str2.val ueOf( ) ) ; / / t r ue

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    User-Defined Object Intro

    Generic objects are used to create user-defineddata types

    var robot = new Obj ect() ;

    robot . name = "Zephyr";

    robot. model = "Guard";

    robot. hasJ etPack = tr ue;

    alert (r obot. name + " " + robot. model );

    robot . att ack = funct i on ( ) { al ert ( ' Zap! ' ) ; };

    robot. attack();

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    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 : " Termi nator" ,

    hasJ etPack: fal se,

    a t tack: f unct ion() {al ert ( ' Hasta l a v is ta! ' ) ;}};

    aler t( robot2.name + " " + robot2.model) ;

    robot2.att ack();

  • 8/13/2019 JavaScriJavaScript Overview.

    12/32

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Object Literals Contd.

    You can build quite large objects this way if you likevar j etpack = t rue;var robot3 = { name: nul l ,

    hasJ etpack: j etpack,

    model : "Pr otocol Droi d",attack: f uncti on() { al ert( "Ahhhh!"); },si deki ck: { name: "Spot",

    model : "Dog",hasJ etpack: f alse,attack: f uncti on() { al ert( "CHOMP!") ; }

    }};

    r obot 3. name = "C- 3PO";al ert ( robot3.name + " " + robot3.model ) ;robot3. si dekick. attack();

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Objects as Associative Arrays

    You can also use an associate array style for object access (or youcould say associative arrays are just objects?)var customers = new Object( );

    customers[ "J ohn Doe"] = "123 Mai n St SD, CA";

    alert (customers[" J ohn Doe"] );

    The advantage here is that you can use property names not knownuntil run timecustomerName = prompt( "Enter name", "" );

    customerAddress = prompt("Enter address", "") ;

    cust omers[ cust omerName] = cust omerAddr ess;

    al ert ( customerName);

    al ert ( customers [ customerName]) ;

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Constructors

    Constructors are special functions that prepare new instances of anobject for use A constructor contains an object prototype that defines the code and

    data that each object instance has by defaultf uncti on Robot( ) { } / / caps j ust conventi onvar guard = new Robot() ;

    f uncti on Robot( needsToFl y){

    i f (needsToFl y == tr ue)this. hasJ etpack = tr ue;

    el seth is .hasJe tpack = fa lse ;

    }/ / create a Robot wi th hasJ etpack == tr uevar guard = newRobot(tr ue);/ / create a Robot wi th hasJ etpack == f alsevar si deki ck = new Robot() ;

  • 8/13/2019 JavaScriJavaScript Overview.

    13/32

  • 8/13/2019 JavaScriJavaScript Overview.

    14/32

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Common Properties and Methods

    Returns true if the propertygive in the string prop will be enumerated in a for/in looppropertyIsEnumerable(prop)

    Returns true if the object serves as the prototype of the object objisPrototypeOf(obj)

    Returns true if the object has an instance propertynamed prop, false otherwisehasOwnProperty(prop)

    Converts the object into an appropriate primitive type, usuallya numbervalueOf()

    Converts the object into a l ocalized string (object-dependent behavior)toLocaleString()

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

    Reference to the function object that served as this objects constructorconstructor

    Reference to the object from which it inherits non-instance propertiesprototype

    DescriptionProperty

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    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 beuseful?

    We leave these questions for you to answer yourself depending on theproject you are working on

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Two Object Models?

    An object model defines the interface to the variousaspects of the browser and document that can bemanipulated by JavaScript.

    In JavaScript, two primary object models are employed1. a browser object model (BOM)

    The BOM provides access to the various characteristics of a browsersuch as the browser window itself, the screen characteristics, thebrowser history and so on.

    2. document object model (DOM).

    The DOM on the other hand provides access to the contents of thebrowser window, namely the document including the various HTMLelements ranging from anchors to images as well as any text thatmay be enclosed by such elements.

  • 8/13/2019 JavaScriJavaScript Overview.

    15/32

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    The Ugly Truth

    Unfortunately, the division between the DOMand the BOM at times is somewhat fuzzy and the

    exact document manipulation capabilities of aparticular browsers implementation ofJavaScript vary significantly.

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    The Big Picture

    Looking at the "big picture" of all various aspects ofJavaScript including its object models. We see fourprimary 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 # 6

  • 8/13/2019 JavaScriJavaScript Overview.

    16/32

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    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. Traditional JavaScript Object Model (NS 2 & IE 3)

    2. Extended Traditional JavaScript Object Model (NS 3)

    3. Dynamic HTML Flavored Object Models

    1. a. IE 4

    2. b. N S 4

    4. Traditional Browser Object Model + Standard DOM (NS6 & Explorer 5)

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Traditional Object Model

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Overview of Core Objects

    An object that describes the basic characteristics of the browser, notably itstype and version.

    Navigator

    Contains the current location of the document being viewed in the form of aURL and its constituent pieces.

    Location

    An object that contains the current window s history list, namely thecollection of the various URLs visited by the user recently.

    History

    An array of the frames in the Window contains any. Each frame in turnreferences another Window object that may also contain more frames.

    Frames[ ]

    An object that contains the various HTML elements and text fragments thatmake up a document. In the traditional JavaScript object model,theDocument object relates roughly the HTML tag.

    Document

    The object that relates to the current browser window.Window

    DescriptionObject

  • 8/13/2019 JavaScriJavaScript Overview.

    17/32

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Document Object

    The Document object provides access to page elementssuch as anchors, form fields, and links as well as pageproperties 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 objectquite a bit document.write( ) , document.writeln( ), document.open( ),

    document.close( )

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Object Access by Document Position

    HTML elements exposed via JavaScript are often placed in arrays orcollections. The order of insertion into the array is based upon theposition in the document.

    For example, the first 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, or other form field indocument.forms[0].elements[0]and so on.

    As arrays we can use the length property to see how many items arein the page.

    The downside of access by position is that if the tag moves thescript may break

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Object Access by Name

    When a tag is named via the name attribute (HTML 4.0 - ,, embedded objects, form elements, and frames) or by idattribute (pretty much every tag) it should be scriptable.

    Given

    we can access the form at window.document.myform and the first

    field as window.document.myform.username

  • 8/13/2019 JavaScriJavaScript Overview.

    18/32

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Object Access by Associative Array

    The collection of HTML objects are storedassociatively in the arrays.

    Given the form named myform we mightaccess 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 # 6

    Event Models

    JavaScript reacts to user actions through eventhandlers (code associated with a particular event orobject and event in the page)

    Common events include Click, MouseOver, MouseOut,etc.

    Events can be registered through HTML event handlerslike onclick or via JavaScript directly

    document.onload = new Function(alert(hi));

    Well see events primarily with links, form items andmouse movement

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    All Together

    Once document objects are accessed either by

    user event or script event we can then modifythe various properties of the elements.

    The following examples on the next slides showreading and writing of form fields as ademonstration of this.

  • 8/13/2019 JavaScriJavaScript Overview.

    19/32

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Meet and GreetWhat's your name?

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Meet and Greet 2What's your name?

    Greeting:

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    The Object Models

    The next few slides present the various object

    models supported pre-standard DOM. InJavaScript 1 we focus primarily on the Netscape3 DOM with some introduction to the non-

    standard DHTML object models.

  • 8/13/2019 JavaScriJavaScript Overview.

    20/32

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Specific Object Models: Netscape 3

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Specific Object Models: Netscape 4

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Specific Object Models: Internet Explorer 3

  • 8/13/2019 JavaScriJavaScript Overview.

    21/32

  • 8/13/2019 JavaScriJavaScript Overview.

    22/32

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    The Standard

    Document Object Model

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    DOM Flavors

    The Document Object Model or DOM is a standard thatmaps HTML and XML documents into objects formanipulation 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 nodemanipulation features via the document object.

    DOM Level 2 Maps all CSS properties

    Note: The later DOM levels also support the earlier objects so classic scriptsshould work under DOM

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    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 eventsand DOM XML are not consistently supported

  • 8/13/2019 JavaScriJavaScript Overview.

    23/32

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Document Trees

    The key to understanding the DOM is how an HTMLdocument is modeled as a tree (Didnt we just talk about

    parse trees!). Consider

    DOM TestDOM Test Heading

    A paragraph of text is just an example

    Yahoo!

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Modeled Document Tree

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Looking at the Tree

    The tree structure follows the structured nature ofHTML. tags encloses and . encloses and so on.

    Each of the items in the tree is called generically a node

    Notice that are different types of nodes correspondingto HTML elements, text strings, and even comments.The types of nodes relevant to most JavaScriptprogrammers is shown on the next slide.

  • 8/13/2019 JavaScriJavaScript Overview.

    24/32

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Node Types

    N o d e T y p e

    N u m b e r

    T y p e D es cr ip t io n E x a m p le

    1 E l e m e n t A n H T M L o r

    XML e l e m e n t .

    < p > < / p >

    2 At t r i b u t e An a t t r i b u te f o ra n H T M L o r

    XML e l e m e n t .

    a l i g n = c e n t e r

    3 T e x t A f r a g m e n t o f

    t e x t t h a t wo u l d

    be en cl os ed bya n H T M L o r

    X M L e l e m e n t

    T h i s i s a t e x t f r a g m e n t !

    8 C o m m e n t A n H T M L

    c o m m e n t

    < ! - - T h i s i s a c o m m e n t - - >

    9 Do c u m e n t T h e r o o t

    d o c u m e n to b j e c t , n a m e l y

    t h e t o p e l e m e n t

    in the parse tree

    < h t m l >

    1 0 Do c u m e n t T y p e A d o c u m e n t

    type def in it ion

    < ! D O C T Y P E H T M L P U B L I C "-

    / / W 3 C / /D T D H T M L 4 . 0 1T r a n s i t i o n a l / / E N"

    " h t t p : / / www.w3 .o r g / T R / h t m l 4 / l o o s e .d t d " >

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Node Relationships

    Look at the tree for

    A paragraph of text is just an example

    Notice that the

    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 # 6

    Node Relationships Contd.

  • 8/13/2019 JavaScriJavaScript Overview.

    25/32

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Accessing Nodes

    The easiest way to access nodes in a documenttree 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

    A paragraph oftext is just an example

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Accessing Nodes Contd.

    Using document.getElementById(p1) we are returned

    an DOM Element object that corresponds to theappropriate 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 # 6

    Accessing Nodes Contd.

    Notice the node value to be 1 (an element), thetype Pcorresponding to the HTML

    tag, andthe nodeValue is null.

    The reason for the null value is that you have to

    look at a text node to see the text within theparent tag. We now need to learn how to movearound the tree. Fortunately there are somegeneric node properties that make this very easyas summarized on the next slide.

  • 8/13/2019 JavaScriJavaScript Overview.

    26/32

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    DOM Node Properties

    D O M N o de P r o pe r t i e s D e sc r i pt i o n

    n o d eN am e Co n t a i n s t h e n am e o f t h e n o d e

    n o d eV a l u e Co n t a i n s t h e v a l u e w i t h i n t h e n o d e ,general ly only appl icable to text nodes

    n o d eTy p e H o l d s a n u m b er co r r e sp o n d in g t o t h e t y p eo f n o d e , a s g i v en i n Tab l e 1 0 - 1

    pa re nt N od e A re fe re nc e t o th e pa re nt no de of th ecurrent object , i f one exists

    ch i l d N o d es A ccess t o l i s t o f ch i l d n o d es

    f i rstChild Reference to the f i r st chi ld node of theelemen t , i f one exists

    lastChild Points to the last chi ld node of the elemen t ,i f one exists

    pr ev io us Si bl in g R ef er en ce to th e p re vi ou s si bl in g of th enode; for example, i f i ts parent node hasmult iple chi ldren

    nextSibl ing Reference to the next sibl ing of the node;for example, i f i ts parent node has mult iplechi ldren

    at t r ibutes The l ist of the at t r ibutes for the element

    o w n er D o cu m en t P o i n t s t o t h e H TM L D o c u m e n t object inw h i ch t h e e l em en t i s co n t a i n ed

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Basic Movement

    Using the common node properties you should beable to move around a tree that you know thestructure 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 nodehad at least two children.

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Basic Movement Contd.

    We need to be careful though when we dont know the treestructure 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 onceyou know the core properties and how to do ifstatements

  • 8/13/2019 JavaScriJavaScript Overview.

    27/32

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    getElementsByName

    Related to getElementById( ) is the DOM method getElementsByName( )which deals with HTML elements identifed by the name attributeincluding: , , , , , , ,and

    Elements using name actually didnt have to have globally unique namesthus the DOM method getElementsByName( ) returns a list of nodes withthe 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 # 6

    Traditional JavaScript Collections

    For backwards compatibility the DOM supports some object

    collections such as document.forms[ ] , document.images[ ] and soforth which were commonly supported amongst JavaScript aware

    browsers.

    Collection Description

    document.anchors[ ] A collection of all the anchors in a page

    specified by

    document.applets[ ] A collection of all the Java applets in a

    page

    document.forms[ ] A collection of all the tags in apage

    document.images[ ] A collection of all images in the pagedefined by tags

    document.links[ ] A collection of all links in the page definedby

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Generalized Element Collections

    Under the DOM you can create an arbitrary collection of elementsusing getElementsByTagName( )

    allparagraphs = document.getElementsByTagName(p);

    You can use many of these methods on nodes themselves to find theelements within a particular element

    allparagraphsinbody= document.body.getElementsByTagName(p);

    para1=document.getElementById(p1);emElements = para1.getElementsByTagName(em);

  • 8/13/2019 JavaScriJavaScript Overview.

    28/32

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Common Tree Starting Points

    Rather than using a built-in collection or a namedstarting point you may simply want to start at a wellknow common tree position such as :

    document.documentElement should be the tag

    document.body tag

    document.doctype should be the statement but may not be and has

    limited value

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Creating Nodes

    You can create nodes and then insert them into thedocument treenewNode = document.createElement(p);

    Of course you may have to then create text nodes to putinside of elementsnewText = document.createTextNode(Hello there);

    Then we will attach things together and attachto thedocumentnewNode.appendChild(newText);

    document.body.appendChild(newNode);

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Create Node Methods

    Method Description Example

    createAttribute( name); 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.

    myAlign =

    document.createAttribute(align);

    createComment(string); Creates an HTML/XML text

    comment of the form where stringis the comment

    content.

    myComment =

    document.createComment(Just a

    comment);

    createElement( tagName) Creates an element of the type

    specified by the string

    parameter tagName

    myHeading =

    document.createElement(h1);

    createTextNode(string) Creates a text node containing

    string.

    newText =

    document.createTextNode(Some

    new text);

  • 8/13/2019 JavaScriJavaScript Overview.

    29/32

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    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 # 6

    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 # 6

    Deleting Nodes

    The Node objects removeChild(child) method is usefulto delete a node out of the tree. You need to run thisnode on the parent of the object you are interested indeleting

    var current = getElementById(p1);currentParent = current.parentNode;currentParent.removeChild(current);

    Note: The removeChild( ) method does return the nodeobject removed.

  • 8/13/2019 JavaScriJavaScript Overview.

    30/32

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Replacing Nodes

    You can also replace a node usingreplaceChild(newchild, oldChild)

    The replaceChildChild( ) method will destroy thecontents of the node replace and does not side

    effect the old value

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Modifying Nodes

    You cant modify an element directly but you can modify itscontents particularly text nodes. Given

    This is a test

    UsetextNode = document.getElementById(p1).firstChild;

    then set the textNodes data property

    textNode.data = Ive been changed!;

    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 mightwant to resort to commonly understood String object methods.

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    Modifying Attributes

    Attributes can be manipulated by DOM methods likegetAttribute(name), setAttribute(attributename, attributevalue )and removeAttribute(attributeName) that work off a particularNode object. You can also check for the existence of attributesusing the hasAttributes( ) method.

    Most people do not use these DOM methods but directly modify the

    attributes of the tag like so

    This is a test

    You would use

    current = document.getElementById(p1);current.align = right;

  • 8/13/2019 JavaScriJavaScript Overview.

    31/32

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    The DOM and HTML

    What you should begin to recognize now is the key to the DOM inmost Web pages is understanding HTML

    The various properties of a node correspond directly to its HTMLattributes. For example given a paragraph tag

    it correspondsto an HTMLParagraphElement with the following properties align,id, className, title, lang, and dir. Notice the mapping from HTMLattributes to object properties is nearly one-to-one except forsome situations like the class attribute which would be a reservedword and thus is renamed className under the DOM.

    Two word attributes like tabindex are represented in the DOM intypical programming camel back form (e.g. tabIndex)

    CSE 130 Programming Language Principles & Paradigms Lecture # 6

    The DOM and HTML

    The ramification of this relationship between HTML and JavaScript

    via the DOM is that the language can now manipulate any arbitraryHTML 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. EvenWYSIWYG 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 # 6

    The DOM and CSS

    The style attribute for an HTML element allows style sheetsproperties to be set inline. The DOM allows access to thisattributes value, for example given

    Test

    then

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

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

  • 8/13/2019 JavaScriJavaScript Overview.

    32/32


Recommended