MostuserswillonlywanttousetheinnerText/innerHTMLandouterText/outerHTMLpropertiesandmethodsdiscussedpreviously.However,thereissomemoreadvancedtextmanipulationthatcanbedoneusinga"textrange"object.TheTextRangeobjectcanbeusedto: Locatethetextforagivenelementoragivenpoint.
Searchforwordsandcharactersinthetextofthedocument.
Movethroughthetextinlogicalunits.
Provideread/writeaccesstotheplaintextandtheHTMLTextinthedocument.
Thisfeaturemightnotbeavailableonnon-MicrosoftWin32platforms.ForthelatestinformationonMicrosoftInternetExplorercross-platformcompatibility,seearticleQ172976intheMicrosoftKnowledgeBase.
Thisarticleconsistsofthefollowingtopics:
OverviewoftheTextRangeObject
WhatDoIDowithaTextRangeObject?
PositioningtheTextRangeObject
CreatingaTextRangeObject
GettingtheContentofaTextRange
ComparingRanges
Commands
OverviewoftheTextRangeObject
TextrangeobjectsareanadvancedfeatureofDynamicHTML(DHTML)thatyoucanusetocarryoutusefultasksrelatedtodynamiccontent,suchassearchingforandselectingtext.Textrangesletyouselectivelypickoutcharacters,words,andsentencesfromadocument.TheTextRangeobjectisanabstractobjectthatcreatesastartandendpositionoverthestreamoftextthatwouldappearintheHTMLdocument.ConsiderthefollowingsimpleHTMLdocument:
<HTML>
<BODY>
<H1>Welcome</H1>
<CENTER><H2>Overview<H2></CENTER>
<P>Besureto<B>Refresh</B>thispage.</P>
</BODY>
</HTML>
Inthisdocument,creatingatextrangeoverthebodyelementwouldpositionthestartatthebeginningofthetextualcontentofthebody,andtheendattheendofthetextualcontentofthebody.Thistextrangewouldcontaintheplaintext"WelcomeOverviewBeSuretoRefreshthispage."
WhatDoIDowithaTextRangeObject?
TherearetwopartstomanipulatingtextwithaTextRangeobject.Thefirstistocreateatextrangesothatthestartandendpositionsencompassthedesiredtext.Thenextstepistoapplyamethodtothetextrange,ormakeacopyofthetexttobeusedelsewhereinthedocument.Oncethetextrangeispositioned,youcansearchfortext,selectthetext,andmakeacopyofthetextanduseitelsewhereinyourdocument.
SeetheTextRangeobjectintheObjectModelReferenceforthepropertiesandmethodssupported.
PositioningtheTextRangeObject
EachtextrangehasastartandanendpositiondefiningthescopeofthetextthatisencompassedbytheTextRangeobject.Whenyoucreateanewtextrange,thestartandendpositionsencompasstheentirecontentbydefault.Usemethodssuchasmove,moveStart,andmoveEndtochangethescopeofthetextrange.
OthermethodscanpositiontheTextRangeobjectwithrespecttoaparticularelement,orapointonthepage.Forexample,moveToElementTextpositionsthetextrangesothatitencompassesthetextcontainedbythegivenelement.ThemoveToPointmethodpositionsthetextrangeatagivenpointwheretheuserclickedamousebutton.Thexandypositionsoftheuser'sclickareknownbythewindow.eventobjectandcanbeusedtopositiontherangeoveragivenpoint.Fromthiscollapsedpoint,therangecanthenbeexpandedtoencompassaword,sentence,orawholetextEdit(theentirepossibleTextRangeobject).
ShowExample
<HTML><HEAD>
<TITLE>moveToPointExample</TITLE>
<script>
functionselectMe(){
varr=document.body.createTextRange();
r.moveToPoint(window.event.x,window.event.y);
r.expand("word");
r.select();
}
</script>
</HEAD>
<BODY>
<H1id=myH1onclick=selectMe()>Clickonawordanditwillhighlight</H1>
</BODY></HTML>
ShowMe
CreatingaTextRangeObject
YoucreateaTextRangeobjectbyapplyingthecreateTextRangemethodtoabody,textArea,orbuttonelement.Youcanalsocreateatextrangefromaselectionmadebytheuser.ThecreateRangemethodontheselectionobjectreturnsatextrange.YoucanusethesamemethodsandpropertiesonthisrangeasyoudoforrangescreatedusingcreateTextRange.
CreatingaTextRangeobjectonthebodywillnotincludethecontentinsideatextAreaorbutton.Conversely,youcannotchangethestartorendpositionofatextrangeoverthetextAreaorbuttontomoveoutsidethescopeoftheseparticularelements.Usethepropertiesprovidedoneachelement,isTextEditandparentTextEdit,towalkthehierarchy.IfthedocumentabovecontainedatextArea,acreateTextRangeonthebodyobjectwouldnotfindthepositionwheretheuseractuallyclicked.Thefollowingreworkstheaboveexampletohandlethiscase.
HideExample
<HTML><HEAD>
<TITLE>moveToPointExample</TITLE>
<scriptfor=documentevent=onclick>
varr
if(window.event.srcElement.isTextEdit)
{
r=window.event.srcElement.createTextRange();
}else{
varel=window.event.srcElement.parentTextEdit;
r=el.createTextRange();
}
r.moveToPoint(window.event.x,window.event.y);
r.expand("word");
r.select();
</script>
</HEAD>
<BODY>
<H1id=myH1>Clickonawordanditwillhighlight</H1>
<TEXTAREA>
There'stextinthiselementtoothatyoucouldclickon
</TEXTAREA>
</BODY></HTML>
ShowMe
GettingtheContentofaTextRange
ThecontentofaTextRangeobjectcanbeviewedwiththetextorhtmlTextpropertyontheTextRangeobject.Thetextpropertyisaread/writepropertythatissimilartotheinnerTextpropertiesontheelementobjects,onlythisreplacesthetextencompassedbyaTextRangeobject.
ThehtmlTextpropertyisaread-onlypropertythatletsyouexaminetheHTMLthatiscontainedwithinthestartandendpointsoftheTextRangeobject.ToaddrichHTMLcontenttothetextrange,usethepasteHTMLmethod.AlthoughyoucanpasteanyHTMLtextthatyouwantintoatextrange,thepasteHTMLmethoddoesnotpreservethehierarchyofthedocument,asdotheinnerHTMLandouterHTMLproperties.AlthoughpasteHTMLwon'tfailifyoupasteinvalidorinappropriatetagsintotherange,theresultingdocumentmightnotlookorbehavethewayyouexpect.IfyoupasteanHTMLfragment,thefragmentisautomaticallyclosedtopreventitfromaffectingsubsequenttextandelements.Forexample,thismeansthatifyourscriptsrelyonordinalpositionsinthedocument'sallcollection,afterapasteHTML,thesourceIndexintothedocument.allcollectionmightpointtoadifferentelement.
ComparingRanges
Youcancreatemorethanonetextrangeatatime,usingthemforindependent,simultaneousaccesstodifferentportionsofthetextinanelement.Youcanalsocopyatextrangebyusingtheduplicatemethod.Thisisusefulifyouwanttemporaryaccesstoaportionoftheoriginalrangebutdon'twanttobotherre-creatingorrestoringtheoriginalrange.YoucandeterminetherelationshipofonetextrangetoanotherbyusingmethodssuchasisEqualandinRange.
Becausetheobjectmodelneverholdsontoatextrange,you'llneedtore-createanyrangewhenevercontrolleavesandthenreentersyourcode.Forexample,anytextrangeobjectscreatedbyaneventhandlerarediscardedwhentheeventhandlerreturns.
YoucandeterminewhetheronerangeisentirelycontainedwithinanothertextrangebyusingtheinRangemethod.YoucandeterminewhethertwotextrangesareidenticalbyusingtheisEqualmethod.Textrangesareidenticaliftheystartandendatexactlythesamepositions.Notethatidenticaltextrangesarealwaysconsideredtobewithinoneanother,meaningtheinRangemethodreturnstrueforthese.
YoucansetthestartorendpointofarangetomatchthestartorendpointofanotherrangebyusingthesetEndPointmethod.Themethodtakestwoparameters:astringdescribingwhichendpointstotransfer,andarangefromwhichthesourceendpointistaken.Thefollowingexamplesetstheendoftheranger1tothestartofr2.
r1.setEndPoint("StartToEnd",r2)
YoucanalsouseStartToStart,EndToStart,andEndToEndtosettheendpoints.
YoucancomparethestartorendpointsoftworangesbyusingthecompareEndPointsmethod.Thismethodcomparestheendpointsandreturns-1,0,or1,indicatingwhethertheendpointofthefirstrangeislessthan,equalto,orgreaterthanthatofthesecond.
Abookmarkisaneasywaytosavethecurrentstartandendpositionsofatextrangeandquicklyrestorethesepositionswhenyouneedthem.YoucreateabookmarkforagivenrangebyusingthegetBookmarkmethod,whichreturnsanopaquestringthatuniquelyidentifiesthebookmark.(Opaquemeansthestringcannotbeexaminedormodified.)YouusethestringwiththemoveToBookmarkmethodtomovethetextrangebacktothesamestartandendpositionsaswhenthebookmarkwascreated.
Commands
Youcanusecommandstoapplyformattingandtocarryoutspecialactionsonthetextofatextrange.YouexecuteacommandbyusingtheexecCommandmethod.Yousupplyacommandidentifierandprovideanyadditionalcommandparameters.Forexample,youcanchangetexttoboldbyusingtheBoldcommandasinthefollowingMicrosoftJScript(compatiblewithECMA262languagespecification)example:
varrng=document.body.createTextRange();
rng.collapse();
rng.expand("sentence");
rng.execCommand("Bold");
ShowMe
Theaboveexamplemakesboldalltextuptothefirstperiodinthedocument.
Notallcommandsareavailableatalltimes.YoucandeterminewhetheracommandisavailableforagiventextrangebyusingthequeryCommandEnabledandqueryCommandSupportedmethods.Foralistofcommands,seeCommandIdentifiers.
Todeterminewhetheragivencommandhasalreadybeenappliedtoatextrange,usethequeryCommandStatemethodtoretrievethestateofthecommand.Thestateistrueifthecommandhasbeenapplied.