The TextRange Object

Note : The TextRange object is Internet Explorer specific. See the Document Range object.

The TextRange object can be used to manipulate any of the document content. It represents one of the major additions to Dynamic HTML, especially considered against the W3C's 'Document Object Model' (http://www.w3.org/pub/WWW/MarkUp/DOM/). One of the more distinctive points of that specification is the ability to be able to manipulate document content through scripting, which the TextRange object more than adequately covers.

A TextRange object can be created by calling the createTextRange() method from the <BODY>, <BUTTON>, <TEXTAREA> or <INPUT TYPE="text"...> elements, or by using the createRange() method on the users current selection through the Selection Object. The text in the resulting TextRange object can then be manipulate in various ways.

Properties
htmlText
The htmlText property returns the contents of the referenced TextRange object, with its HTML intact.

text
The text property returns the contents of the referenced TextRange object as plain text, regardless of any HTML formatting of the content.

For example, consider the following HTML fragment:

this is the <STRONG>contents</STRONG> of a TextRange object

The htmlText property of the TextRange would be:

this is the <STRONG>contents</STRONG> of a TextRange object

whereas the text property would be:

this is the contents of a TextRange object

Methods
collapse
The collapse method sets an insertion point at either the beginning (collapse(true)), or end (collapse(false)) of the referenced TextRange object. Insertion points are useful, as then various execCommand commands (see below) can be executed on the text range to insert new element into the HTML. For example, select some of the text below (the white paragraph) and then press the right mouse button. When this happens the following script function is executed:

. . .
set selectedRange = document.selection.createRange()
selectedRange.collapse(false)
selectedRange.execCommand "InsertHorizontalRule","HR1"

This creates a TextRange object from the current Selection Object, then forces the insertion point to the end of the resulting TextRange object and inserts a <HR> element with an ID attribute/property setting of HR1

Select some of the text, then press the right mouse button to insert a <HR> element anywhere in this text.

compareEndPoints
The compareEndPoints method can be used to compare the ends (either starting, or finishing ends) of two TextRange objects and returns a value of "-1", "0" or "1" depending on whether the compared TextRange object's end point is greater than, equal to, or less than the referenced

duplicate
The duplicate method can be used to create a temporary copy of a referenced TextRange object. For example:

set TR2 = TR1.duplicate()

would create a TextRange object TR2 that is a copy of the TextRange object TR1

ExecCommand
The Internet Explorer 4.0 specific execCommand method can be used to execute a number of commands over a TextRange object. The syntax is:

Boolean = object.execCommand(command [, bool [, value]])

where:

command
is one of the possible Command Identifier (see below)
bool
A boolean value setting whether to show any possible interface that the particular command may have
value
A possible value, the contents/data type of which are determined by the specific command used

The possible Command Identifiers are:

Command Description Value
BackColor sets the background colour of the referenced text #rrggbb|Colour name
Bold Wraps a <B> element around the referenced object -
Copy Copies the referenced object to the clipboard -
CreateBookmark Wraps a <A NAME="..."> element around the referenced object String - bookmark to use
Create Link Wraps a <A HREF="..."> element around the referenced object String - URL for link
Cut Copies the referenced object to the clipboard, then removes it from the document -
Delete Deletes the referenced object -
FontName Sets the typeface for the referenced object String - Font Name
FontSize Sets the font size for the referenced object String - size
ForeColor Sets the foreground (i.e. text) colour for the referenced object #rrggbb | Colour Name
FormatBlock Wraps a specified block-level element around the referenced object String - block level element to use
Indent Indents the referenced object -
InsertButton Inserts a <BUTTON> element at the current insertion point String - ID value
InsertFieldSet Inserts a <FIELDSET> element at the current insertion point String - ID value
InsertHorizontalRule Inserts a <HR> element at the current insertion point String - ID value
InsertIFrame Inserts a <IFRAME> element at the current insertion point String - SRC value
InsertInputButton Inserts a <INPUT TYPE="button"> element at the current insertion point String - ID value
InsertInputCheckbox Inserts a <INPUT TYPE="checkbox"> element at the current insertion point String - ID value
InsertInputFileUpload Inserts a <INPUT TYPE="FileUpload"> element at the current insertion point String - ID value
InsertInputHidden Inserts a <INPUT TYPE="hidden"> element at the current insertion point String - ID value
InsertInputPassword Inserts a <INPUT TYPE="password"> element at the current insertion point String - ID value
InsertInputRadio Inserts a <INPUT TYPE="radio"> element at the current insertion point String - ID value
InsertInputReset Inserts a <INPUT TYPE="reset"> element at the current insertion point String - ID value
InsertInputSubmit Inserts a <INPUT TYPE="submit"> element at the current insertion point String - ID value
InsertInputText Inserts a <INPUT TYPE="text"> element at the current insertion point String - ID value
InsertMarquee Inserts a <MARQUEE> element at the current insertion point String - ID value
InsertOrderedList Inserts a <OL> element at the current insertion point String - ID value
InsertParagraph Inserts a <P> element at the current insertion point String - ID value
InsertSelectDropdown Inserts a <SELECT TYPE="dropdown"> element at the current insertion point String - ID value
InsertSelectListbox Inserts a <SELECT TYPE="Listbox"> element at the current insertion point String - ID value
InsertTextArea Inserts a <TEXTAREA> element at the current insertion point String - ID value
InsertUnorderedList Inserts a <IL> element at the current insertion point String - ID value
Italic Wraps a <I> element around the referenced object -
JustifyCenter Centers the referenced object -
JustifyFull Full justifies the referenced object -
JustifyLeft Left justifies the referenced object -
JustifyRight Right justifies the referenced object -
Outdent Outdents the referenced object -
OverWrite Sets the typing mode - insert or over-write Boolean - true=over-write, false=insert
Paste Places clipboard contents at the current insertion point (can only paste text copied by the copy command in script -
PlayImage Starts playing any dynamic (i.e. video, animated GIF's etc) images with the referenced object -
Refresh Reloads the source of the current document -
RemoveFormat Removes formatting for the referenced object -
RemoveParaFormat Removes any paragraph formatting for the referenced object -
SelectAll Selects the whole document text -
StopImage Stops playing of all dynamic images -
Underline Wraps a <U> around the referenced object -
Unlink Removes a link -
Unselect Empties any selections from the document -

Note : Different Command Identifiers are supported 4.0 for the TextRange object (or the Document Object object).

expand
The expand method expands a TextRange object to totally cover any partial units. By using differing arguments, it can expand to cover characters, words, sentences, or an entire editable text range. For example, suppose the following is a users current text selection:

I'm only partly selected

Using:

bIsExpanded=TextRangereference.expand("word")

would return true (i.e. bIsExpanded=true) if the TextRange object was successfully expanded to cover the whole of the word 'partly'. Note that the expand method expands the TextRange at both ends to cover the amount specified in the method argument (this can be character, word, sentence or textedit)

findText
The findText method searches for text in the given TextRange object and if it finds the text, positions the TextRange object around the text. For example:

set TRange=document.body.createTextRange()
TRange.findText("HTMLib")
. . .

would search the whole document for the text "HTMLib".

getBookmark
The getBookmark method can be used to create a 'bookmark' for the referenced TextRange object, which can then be moved to later, using the moveToBookmark method (see below). This is useful when managing an entire document as a TextRange object, because it allows script functions to navigate back to certain points of the TextRange object.

inRange
The inRange method allows a script function to determine where a referenced TextRange object is contained within another TextRange object. For example:

bIsIn=TR1.inRange(TR2)

would return true (bIsIn=true) is the TextRange TR1 was contained in the TextRange TR2.

isEqual
Two separate TextRange objects are deemed to be equal if they're start and end points are the same position within the document content. The isEqual method can be used to determine whether or not two TextRange objects are considered equal.

bIsEqual=TR1.isEqual(TR2)

would return true is the TextRange object TR1 is equal to the TextRange object TR2.

move
The move method can be used to move a TextRange object by a set number of units. Possible units are character, word, sentence or textedit. The optional argument count can be used to move the TextRange a set number of units. For example, click the button below. It'll create a TextRange (with the button text), then move the text range 3 words, expand it by a word and highlight the resulting TextRange object.

The script code is:

set Range=document.all("btn1").createTextRange()
Range.move "word",3
Range.expand "word"
Range.select()

Note : Moving the collapsed TextRange by three words positions its start point between the third and fourth words, so it's the fourth word that is selected and highlighted.

moveEnd
The moveEnd method alters the size (and content) of the referenced TextRange object by moving its end point by a set number of units (again, these are character, word, sentence and textedit). For example, if we added:

Range.moveEnd "word",1

to the above example, it would highlight "very long" as the TextRange, instead of just "long".

moveStart
Like the moveEnd method, the moveStart method changes the start point of the referenced TextRange object (again in character, word, sentence, or textedit units.

moveToBookmark
The moveToBookmark moves the referenced TextRange object to a bookmark, previously defined using the getBookmark method (described above).

moveToElementText
The moveToElementText method moves the referenced TextRange's start and end points to encompass the text of any element contained in the original TextRange object. For example, the button below contained some <STRING> text that contains some <EM> emphasised text. Clicking it once will move the TextRange (created from the whole button) to the contents of the <STRong> element, clicking it twice will move the TextRange object to the text in the <EM> element.

It's clear how useful the moveToElementText method could be given TextRange objects that encompass an entire document. Any element in the document could be made into a TextRange object, event though most elements don't support direct TextRange object creation.

moveToPoint
The moveToPoint method can be used to create an initially empty TextRange object whose start and end points are specified in the x and y arguments of the method. The resulting TextRange object can then be expanded (using the expand method (described above) or the moveEnd and moveStart methods to encompass a certain amount of text.

parentElement
Every TextRange object has a parentElement property that contains a reference to the element that totally encloses the contents of the TextRange element. The element object reference returned represents the lowest element object (in the document hierarchy) that totally encloses the referenced TextRange. For example, the parentElement reference for any selected TextRange objects in the collapse method, is the <P> element.

pasteHTML
The pasteHTML method pastes the given HTML string into the contents of the referenced TextRange, over-writing the existing TextRange contents. The pasteHTML method will never fail, although to ensure the best results, you should take care to only use correct HTML in the pasteHTML method. For example <BUTTON> elements cannot be nested, so TextRange objects created from <BUTTON> elements should not have any <BUTTON> HTML inserted into them with the pasteHTML method.

queryCommandEnabled
The Internet Explorer 4.0 specific queryCommandEnabled method allows you to determine whether a specific command (as defined by its command identifier is available for the referenced object. As mentioned before, certain commands aren't available for the respective Document Object or Text Range objects, so the queryCommandEnabled method should be used to determine whether the command is enabled for the referenced object before attempting to use the command. The queryCommandEnabled method takes one argument, which should be a string containing one of the Command Identifiers.

queryComandIndeterm
The Internet Explorer 4.0 specific queryCommandIndeterm method can be used to determine whether a specific command is in the indeterminate state or not. It accepts one argument - a string value containing the Command Identifier in question.

queryCommandState
The queryCommandState method is used to determine the state of any command issued with the execCommand method (see above). It returns true if the command was successfully carried out on the referenced object, false if the command failed.

queryCommandSupported
queryCommandSupported method can be used to determine whether the command is currently on or off. It accepts a single argument of a string value defining the Command Identifier to be queried and returns a boolean value of true is the command is on for the referenced object, or false if it isn't.

queryCommandText
The Internet Explorer 4.0 specific queryCommandText method can be used to determine the the string associated with a command. It accepts the standard string argument of the Command Identifier together with a string value which can be either Name or StatusText which specified whether to return the short name of the command in question, or the status bar text which may appear with the specific command.

queryCommandValue
The Internet Explorer 4.0 specific queryCommandValue method can be used to determine the value argument used in the execCommand method. See the Command Identifiers for details of the values used with certain commands.

scrollIntoView
The scrollIntoView method is one of the standard Dynamic HTML methods and can be used to force the current viewing window to scroll to a referenced TextRange object. It accepts a boolean argument (true or false) which determines whether the window should be scrolled so that the referenced TextRange object is at the top (true) or bottom (false) of the window. For example, the button below will select the contents of the <BUTTON> element in the move method and scroll it into view, so that it's at the top of the viewing window.

select
The select method highlights the referenced TextRange object in whatever highlighting styles are set by the users system for highlighted text (for example, text selected in a document).  Note that if you change the position of the range with e.g. moveEnd or other methods, those changes are NOT seen by the user until you call the .select method.

setEndPoint
The setEndPoint method sets the end point of one TextRange object, based on the contents of another TextRange object. It accepts two arguments - one specifying which end points should be matched (this can be either StartToEnd, StartToStart, EndToStart or EndToEnd) and a reference to the TextRange object whose end point is being matched.

Questions:

Comments:

In FireFox, or other Mozilla based browsers, most of that is accomplised with:


textarea.selectionStart = start;
textarea.selectionEnd = end;
or
textarea.setSelectionRange(start, end);

Here is an example that first finds where the selection (if any) is, and then inserts some text around it and finally reselects the text after the insertion.


<a href="javascript:void(0);" onclick="surroundText('[b]', '[/b]', document.post_form.msg_body); return false;">


where surroundText is defined as:


function surroundText(text1, text2, textarea)
{
	// Can a text range be created?
	if (typeof(textarea.caretPos) != "undefined" && textarea.createTextRange)
	{
		var caretPos = textarea.caretPos;

		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text1 + caretPos.text + text2 + ' ' : text1 + caretPos.text + text2;
		caretPos.select();
	}
	// Mozilla text range wrap.
	else if (typeof(textarea.selectionStart) != "undefined")
	{
		var begin = textarea.value.substr(0, textarea.selectionStart);
		var selection = textarea.value.substr(textarea.selectionStart, textarea.selectionEnd - textarea.selectionStart);
		var end = textarea.value.substr(textarea.selectionEnd);
		var newCursorPos = textarea.selectionStart;
		var scrollPos = textarea.scrollTop;

		textarea.value = begin + text1 + selection + text2 + end;

		if (textarea.setSelectionRange)
		{
			if (selection.length == 0)
				textarea.setSelectionRange(newCursorPos + text1.length, newCursorPos + text1.length);
			else
				textarea.setSelectionRange(newCursorPos, newCursorPos + text1.length + selection.length + text2.length);
			textarea.focus();
		}
		textarea.scrollTop = scrollPos;
	}
	// Just put them on the end, then.
	else
	{
		textarea.value += text1 + text2;
		textarea.focus(textarea.value.length - 1);
	}
}

See also:

Code: