Internet Explorer supports text ranges, which you can use to replace text in Web pages. A full discussion of text ranges is beyond the scope of this book, but here’s a starter example, textranges.html, which appears in Figure 11.20.
Figure 11.20: The textranges.html application
When you click the button, the text in the page is selected and rewritten, as shown in Figure 11.21.
Figure 11.21: Replacing text in the textranges.html application
This example starts with a button connected to a function named replaceText:
<body> <center> <h1> Using TextRanges </h1> </center> <input type="button" value="Click me" onclick="replaceText()"> <br> <br> . . . </body>
and you can also add a <div> element with the ID div1:
<body> <center> <h1> Using TextRanges </h1> </center> <input type="button" value="Click me" onclick="replaceText()"> <br> <br> <div > Click the button to replace this text. </div> </body>
When the user clicks the button, the replaceText function is called, which starts by creating a text range that can select text:
<head> <title> Using TextRanges </title> <script language="JavaScript"> function replaceText() { var range = document.body.createTextRange(); . . . } </script> </head>
Next, you create an object corresponding to the <div> element:
<head> <title> Using TextRanges </title> <script language="JavaScript"> function replaceText() { var range = document.body.createTextRange(); var div = document.getElementById("div1"); . . . } </script> </head>
and then you can move your text range to encompass the <div> element with the range’s moveToElementText method:
<head> <title> Using TextRanges </title> <script language="JavaScript"> function replaceText() { var range = document.body.createTextRange(); var div = document.getElementById("div1"); range.moveToElementText(div); . . . } </script> </head>
Now that you’ve enclosed the <div> element inside a text range, you can use the range’s pasteHTML method to overwrite the <div> element’s HTML like this:
<head> <title> Using TextRanges </title> <script language="JavaScript"> function replaceText() { var range = document.body.createTextRange(); var div = document.getElementById("div1"); range.moveToElementText(div); range.pasteHTML("Here is the new text."); } </script> </head>
Besides pasting HTML into a text range, you can also move them around a Web page. The major drawback, of course, is that text ranges are supported in Internet Explorer only.