Creating Text Ranges


To create a text range, you can use the <BODY> element's createTextRange method (see Table 9.12). After you have a text range, several methods (as you can see in Table 11.15 such as move , moveStart , moveEnd , moveToElementText , expand , and so on) enable you to position the text range as you want it.

Here's an example we've already seen in Chapter 5it's Listing 05-15.html on the web site. In this case, I create a text range, move it to enclose an element's text, and then use the text range's pasteHTML method to replace the text in the range, all when the user clicks a button:

 <HTML>      <HEAD>          <TITLE>              Using Text Ranges          </TITLE>          <SCRIPT LANGAUGE="JavaScript">              <!--             function replaceText()              {  if(document.body.isTextEdit){   var range = document.body.createTextRange()   range.moveToElementText(div1)   range.pasteHTML("Here is the replacement text!")   }  }              // -->          </SCRIPT>      </HEAD>      <BODY>           <H1>Using Text Ranges</H1>          <INPUT TYPE=BUTTON VALUE="Click Me!" onclick="replaceText()">          <BR>          <BR>          <DIV ID="div1" STYLE="font-family:Arial, sans-serif; font-weight:bold">              Click the button to replace all this text.          </DIV>      </BODY>  </HTML> 

You can see the results in Chapter 5, in Figure 5.12, where I've clicked the button and replaced the original text with new text.

You also can create text ranges for controls such as buttons , text fields, text areas, and so on. Here's an example that creates a text range corresponding to the text in the third button in a document, and uses the text range's text property to change the button caption to Click Me!:

 <SCRIPT LANGUAGE="JavaScript">      var buttons = document.all.tags("BUTTON")      var range = buttons[2].createTextRange()      range.text = "Click Me!"  </SCRIPT> 


Inside Javascript
Inside JavaScript
ISBN: 0735712859
EAN: 2147483647
Year: 2005
Pages: 492
Authors: Steve Holzner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net