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:
Welcome
Overview
BesuretoRefreshthispage.
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
ShowMe
CreatingaTextRangeObject
YoucreateaTextRangeobjectbyapplyingthecreateTextRangemethodtoabody,textArea,orbuttonelement.Youcanalsocreateatextrangefromaselectionmadebytheuser.ThecreateRangemethodontheselectionobjectreturnsatextrange.YoucanusethesamemethodsandpropertiesonthisrangeasyoudoforrangescreatedusingcreateTextRange.
CreatingaTextRangeobjectonthebodywillnotincludethecontentinsideatextAreaorbutton.Conversely,youcannotchangethestartorendpositionofatextrangeoverthetextAreaorbuttontomoveoutsidethescopeoftheseparticularelements.Usethepropertiesprovidedoneachelement,isTextEditandparentTextEdit,towalkthehierarchy.IfthedocumentabovecontainedatextArea,acreateTextRangeonthebodyobjectwouldnotfindthepositionwheretheuseractuallyclicked.Thefollowingreworkstheaboveexampletohandlethiscase.
HideExample
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();
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.