04.11.2015 Views

javascript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 11: DOM Levels 2 and 3<br />

Complex Selection in IE Ranges<br />

Complex ranges can be created in IE by moving the range selection around in specific increments. This<br />

can be done using four methods: move() , moveStart() , moveEnd() , and expand() . Each of these<br />

methods accepts two arguments: the type of unit to move and the number of units to move. The type of<br />

units to move is one of the following string values:<br />

❑<br />

❑<br />

❑<br />

❑<br />

“ character “ — Moves a point by one character<br />

“ word “ — Moves a point by one word (a sequence of non–white - space characters)<br />

“ sentence “ — Moves a point by one sentence (a sequence of characters ending with a period,<br />

question mark, or exclamation point)<br />

“ textedit “ — Moves a point to the start or end of the current range selection<br />

The moveStart() method moves the starting point of the range by the given number of units,<br />

whereas the moveEnd() method moves the end point of the range by the given number of units, as<br />

shown in the following example:<br />

range.moveStart(“word”, 2);<br />

range.moveEnd(“character”, 1);<br />

//move the start point by two words<br />

//move the ending point by two words<br />

You can also use the expand() method to normalize the range. The expand() method makes sure that any<br />

partially selected units become fully selected. For example, if you selected only the middle two characters<br />

of a word, you can call expand( “ word “ ) to ensure that the entire word is enclosed by the range.<br />

The move() method first collapses the range (making the start and end points equal), and then moves<br />

the range by the specified number of units, as shown in the following example:<br />

range.move(“character”, 5);<br />

//move over five characters<br />

After using move() , the start and end points are equal, so you must use either moveStart() or<br />

moveEnd() to once again make a selection.<br />

Interacting with IE Range Content<br />

Interacting with a range ’ s content in IE is done through either the text property or the pasteHTML()<br />

method. The text property, used previously to retrieve the text content of the range, can also be used to<br />

set the text content of the range. Here is an example:<br />

var range = document.body.createTextRange();<br />

range.findText(“Hello”);<br />

range.text = “Howdy”;<br />

If you run this code against the same Hello World code shown earlier, the HTML result is as follows:<br />

< p id=”p1” > < b > Howdy < /b > World < /p ><br />

Note that all the HTML tags remained intact when setting the text property.<br />

360

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!