function foo() {
var selObj = window.getSelection();
alert(selObj);
var selRange = selObj.getRangeAt(0);
// do stuff with the range
}
In JavaScript, when a selection object is passed to a function expecting a string (like window.alert
or document.write
), a string representation of it (i.e. the selected text) is passed instead. This makes the selection object appear like a string, when it is really an object with its own properties and methods. Specifically, the return value of calling the toString() method of the Selection object is passed.
In the above example, selObj is automatically "converted" when passed to window.alert. However, to use a JavaScript String property or method such as length or substr, you must manually call the toString method.
Page last modified 03:01, 16 Sep 2007 by Mgjbot