Tải bản đầy đủ - 0 (trang)
Chapter 10. Document Object Model (DOM): Objects and Collections

Chapter 10. Document Object Model (DOM): Objects and Collections

Tải bản đầy đủ - 0trang

Towriteit,ittookthreemonths;toconceiveitthree

minutes;tocollectthedatainit—allmylife.

—F.ScottFitzgerald

Siblingrivalryisinevitable.Theonlysurewayto

avoiditistohaveonechild.

—NancySamalin

Outline

10.1 Introduction

10.2 ModelingaDocument:DOMNodesandTrees

10.3 TraversingandModifyingaDOMTree

10.4 DOMCollections

10.5 DynamicStyles

10.6 SummaryoftheDOMObjectsandCollections

10.7 WebResources



10.1.Introduction

InthischapterweintroducetheDocumentObjectModel

(DOM).TheDOMgivesyouaccesstoalltheelementsonaweb

page.Insidethebrowser,thewholewebpage—paragraphs,

forms,tables,etc.—isrepresentedinanobjecthierarchy.

UsingJavaScript,youcancreate,modifyandremoveelements

inthepagedynamically.

Previously,bothInternetExplorerandNetscapehaddifferent

versionsofDynamicHTML,whichprovidedsimilarfunctionality

totheDOM.However,whiletheyprovidedmanyofthesame

capabilities,thesetwomodelswereincompatiblewitheach

other.Inanefforttoencouragecross-browserwebsites,the

W3CcreatedthestandardizedDocumentObjectModel.Firefox



2,InternetExplorer7,andmanyothermajorbrowsers

implementmostofthefeaturesoftheW3CDOM.

ThischapterbeginsbyformallyintroducingtheconceptofDOM

nodesandDOMtrees.Wethendiscusspropertiesandmethods

ofDOMnodesandcoveradditionalmethodsofthedocument

object.Wealsodiscusshowtodynamicallychangestyle

properties,whichenablesyoutocreatemanytypesofeffects,

suchasuser-definedbackgroundcolorsandanimations.Then,

wepresentadiagramoftheextensiveobjecthierarchy,with

explanationsofthevariousobjectsandproperties,andwe

providelinkstowebsiteswithfurtherinformationonthetopic.

SoftwareEngineeringObservation10.1

WiththeDOM,XHTMLelementscanbe

treatedasobjects,andmanyattributesof

XHTMLelementscanbetreatedas

propertiesofthoseobjects.Then,objects

canbescripted(throughtheirid

attributes)withJavaScripttoachieve

dynamiceffects.



10.DocumentObjectModel(DOM):

ObjectsandCollections

Objectives

Inthischapteryouwilllearn:

HowtouseJavaScriptandtheW3CDocumentObject

Modeltocreatedynamicwebpages.

TheconceptsofDOMnodesandDOMtrees.

Howtotraverse,editandmodifyelementsinanXHTML

document.

HowtochangeCSSstylesdynamically.

TocreateJavaScriptanimations.

Ourchildrenmaylearnaboutheroesofthepast.Our

taskistomakeourselvesarchitectsofthefuture.

—JomoMzeeKenyatta

Thoughleavesaremany,therootisone.

—WilliamButlerYeats

ThethingthatimpressesmemostaboutAmericais

thewayparentsobeytheirchildren.

—DukeofWindsor

Mostofusbecomeparentslongbeforewehave

stoppedbeingchildren.

—MignonMcLaughlin



Towriteit,ittookthreemonths;toconceiveitthree

minutes;tocollectthedatainit—allmylife.

—F.ScottFitzgerald

Siblingrivalryisinevitable.Theonlysurewayto

avoiditistohaveonechild.

—NancySamalin

Outline

10.1 Introduction

10.2 ModelingaDocument:DOMNodesandTrees

10.3 TraversingandModifyingaDOMTree

10.4 DOMCollections

10.5 DynamicStyles

10.6 SummaryoftheDOMObjectsandCollections

10.7 WebResources



10.1.Introduction

InthischapterweintroducetheDocumentObjectModel

(DOM).TheDOMgivesyouaccesstoalltheelementsonaweb

page.Insidethebrowser,thewholewebpage—paragraphs,

forms,tables,etc.—isrepresentedinanobjecthierarchy.

UsingJavaScript,youcancreate,modifyandremoveelements

inthepagedynamically.

Previously,bothInternetExplorerandNetscapehaddifferent

versionsofDynamicHTML,whichprovidedsimilarfunctionality

totheDOM.However,whiletheyprovidedmanyofthesame

capabilities,thesetwomodelswereincompatiblewitheach

other.Inanefforttoencouragecross-browserwebsites,the

W3CcreatedthestandardizedDocumentObjectModel.Firefox



2,InternetExplorer7,andmanyothermajorbrowsers

implementmostofthefeaturesoftheW3CDOM.

ThischapterbeginsbyformallyintroducingtheconceptofDOM

nodesandDOMtrees.Wethendiscusspropertiesandmethods

ofDOMnodesandcoveradditionalmethodsofthedocument

object.Wealsodiscusshowtodynamicallychangestyle

properties,whichenablesyoutocreatemanytypesofeffects,

suchasuser-definedbackgroundcolorsandanimations.Then,

wepresentadiagramoftheextensiveobjecthierarchy,with

explanationsofthevariousobjectsandproperties,andwe

providelinkstowebsiteswithfurtherinformationonthetopic.

SoftwareEngineeringObservation10.1

WiththeDOM,XHTMLelementscanbe

treatedasobjects,andmanyattributesof

XHTMLelementscanbetreatedas

propertiesofthoseobjects.Then,objects

canbescripted(throughtheirid

attributes)withJavaScripttoachieve

dynamiceffects.



10.2.ModelingaDocument:DOMNodes

andTrees

Aswesawinpreviouschapters,thedocument's

getElementByIdmethodisthesimplestwaytoaccessa

specificelementinapage.Inthissectionandthenext,we

discussmorethoroughlytheobjectsreturnedbythismethod.

ThegetElementByIdmethodreturnsobjectscalledDOM

nodes.EveryelementinanXHTMLpageismodeledintheweb

browserbyaDOMnode.Allthenodesinadocumentmakeup

thepage'sDOMtree,whichdescribestherelationshipsamong

elements.Nodesarerelatedtoeachotherthroughchild-parent

relationships.AnXHTMLelementinsideanotherelementissaid

tobeachildofthecontainingelement.Thecontainingelement

isknownastheparent.Anodemayhavemultiplechildren,but

onlyoneparent.Nodeswiththesameparentnodearereferred

toassiblings.

Somebrowsershavetoolsthatallowyoutoseeavisual

representationoftheDOMtreeofadocument.Wheninstalling

Firefox,youcanchoosetoinstallatoolcalledtheDOM

Inspector,whichallowsyoutoviewtheDOMtreeofanXHTML

document.Toinspectadocument,Firefoxuserscanaccessthe

DOMInspectorfromtheToolsmenuofFirefox.IftheDOM

inspectorisnotinthemenu,runtheFirefoxinstallerand

chooseCustomintheSetupTypescreen,makingsuretheDOM

InspectorboxischeckedintheOptionalComponentswindow.

MicrosoftprovidesaDeveloperToolbarforInternetExplorer

thatallowsyoutoinspecttheDOMtreeofadocument.The

toolbarcanbedownloadedfromMicrosoftat

go.microsoft.com/fwlink/?LinkId=92716.Oncethetoolbaris

installed,restartthebrowser,thenclickthe iconattheright

ofthetoolbarandchooseIEDeveloperToolbarfromthemenu.

Figure10.1showsanXHTMLdocumentanditsDOMtree

displayedinFirefox'sDOMInspectorandinIE'sWebDeveloper



Toolbar.

Figure10.1.Demonstrationofadocument'sDOMtree.

CodeView:



1

2
3"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"

4

5

6

7

8

9DOMTreeDemonstration

10

11

12

AnXHTMLPage



13

ThispagecontainssomebasicXHTMLelements.Weu

14DOMInspectorandtheIEDeveloperToolbartoview

15ofthedocument,whichcontainsaDOMnodeforeve

16thedocument.



17

Here'salist:



18


    19
  • One


  • 20
  • Two


  • 21
  • Three


  • 22


23

24

























a)TheXHTMLdocumentisrenderedinFirefox.

[Viewfullsizeimage]



b)TheFirefoxDOMinspectordisplaysthedocumenttreeinthelef

rightpanelshowsinformationaboutthecurrentlyselectednode.

[Viewfullsizeimage]



c)TheInternetExplorerWebDeveloperToolbardisplaysmuchof

informationastheDOMinspectorinFirefoxinapanelatthebotto

browserwindow.

[Viewfullsizeimage]



TheXHTMLdocumentcontainsafewsimpleelements.We

explaintheexamplebasedontheFirefoxDOMInspector—the

IEToolbardisplaysthedocumentwithonlyminordifferences.A

nodecanbeexpandedandcollapsedusingthe+and-buttons

nexttothenode'sname.Figure10.1(b)showsallthenodesin

thedocumentfullyexpanded.Thedocumentnode(shownas

#document)atthetopofthetreeiscalledtherootnode,

becauseithasnoparent.Belowthedocumentnode,theHTML

nodeisindentedfromthedocumentnodetosignifythatthe

HTMLnodeisachildofthe#documentnode.TheHTMLnode

representsthehtmlelement(lines7–24).

TheHEADandBODYnodesaresiblings,sincetheyareboth

childrenoftheHTMLnode.TheHEADcontainstwo#comment



nodes,representinglines5–6.TheTITLEnodehasachildtext

node(#text)containingthetextDOMTreeDemonstration,visiblein

therightpaneoftheDOMinspectorwhenthetextnodeis

selected.TheBODYnodecontainsnodesrepresentingeachof

theelementsinthepage.NotethattheLInodesarechildrenof

theULnode,sincetheyarenestedinsideit.

Also,noticethat,inadditiontothetextnodesrepresentingthe

textinsidethebody,paragraphsandlistelements,anumberof

othertextnodesappearinthedocument.Thesetextnodes

containnothingbutwhitespace.WhenFirefoxparsesanXHTML

documentintoaDOMtree,thewhitespacebetweensibling

elementsisinterpretedastextandplacedinsidetextnodes.

InternetExplorerignoreswhitespaceanddoesnotconvertit

intoemptytextnodes.Ifyourunthisexampleonyourown

computer,youwillnoticethattheBODYnodehasa#comment

childnodenotpresentaboveinboththeFirefoxandInternet

ExplorerDOMtrees.Thisisaresultofthecopyrightlineatthe

endoftheexamplefilethatyoudownloaded.

ThissectionintroducedtheconceptofDOMnodesandDOM

trees.ThenextsectionconsidersDOMnodesinmoredetail,

discussingmethodsandpropertiesofDOMnodesthatallowyou

tomodifytheDOMtreeofadocumentusingJavaScript.



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 10. Document Object Model (DOM): Objects and Collections

Tải bản đầy đủ ngay(0 tr)

×