text property
Sets or retrieves the text contained within the range.
Syntax
| JavaScript | |
|---|
Property values
Type: String
the contained text.
Standards information
- Document Object Model (DOM) Level 1 Specification, Section 2.5.5
Remarks
The text formats within the current context of the document. You cannot set this property while the document is loading. Wait for the onload event before attempting to set this property.
This feature might not be available on non-Microsoft Win32 platforms.
See also
Send comments about this topic to Microsoft
Build date: 2/14/2012
This property incorrectly trims trailing CR/LF from text ranges. The trailing CR/LF characters will still actually exist in the TextRange content, and will be reported if the text range is modified so a non-CR/LF character is at the end, but the strings returned in the text and htmlText properties will not include these trailing CR/LF characters. This example has been tested with IE7, and illustrates the differences between the processing of the value and the TextRange text:
<textarea id="txt">CR/LF here:
</textarea>
<script>
var txt = document.getElementById("txt");
alert(encodeURIComponent(txt.value)); // CR%2FLF%20here%3A%0D%0A
alert(encodeURIComponent(txt.createTextRange().text)); // CR%2FLF%20here%3A
</script>
This behavior makes it very difficult to detect the boundaries of selected text in editor-style applications. The only way I have found to work around this is to:
- make a duplicate of the selection
- collapse it to the start or end
- set its text to " "
- move the end of the selection to the end of the duplicate
- record the selection's text minus the new end space character
- move the duplicate's start -1 to encompass the end space character
- set the duplicate's text back to ""
In addition to being painfully complex for such a simple requirement, this workaround also has a side effect of adding two steps into the Undo buffer, one to add the extra space and one to remove it. Please give us some way of retrieving the full text in the range, not just the text that you think developers would find useful! I don't care if it's a new, differently-named property or whatever. The above workaround is just too much of a kludge, but it is the only approach I've found that works consistently.
edit: I found that if you do document.execCommand("undo") after step #5, you can omit steps #6 and #7 and preserve the Undo buffer correctly. Still not a good solution per se, but at least the Undo buffer isn't broken by using that.