It has been discussed a lot how to get the nodes that represent the current selection in a certain browser window. There is the W3C way of doing it, using the Range and Selection objects and there is the IE implementation with selection, TextRange and ControlRange. This article explains how to get the nodes which are currently selected in an browser independent way. It even allows to surround sub-selections in text nodes, to exactly represent the user's selection.
The code was created in the Mediabird project, a program that features social eLearning and flash-card based studying. The attached file is licensed under the GPLv3. If you need a different license, please contact the author.
The function getSelection takes four arguments:
- context: The document object, either null if you want to use the default document or a particular document object which might refer to a document object of a different IFrame, window or frame.
- disableSurrounding: Do not put SPAN nodes around text ranges to exaclty match the user's selection. Instead, only whole nodes are returned. Defaults to false.
- returnNullIfEmpty: If true, the function will immediately return null if there is no selection, i.e. the selection is collapsed.
- allowTextNodes: Normally, only element nodes are returned. If you specify true, also text nodes will be returned.
How does the algorithm work? It determines the last and first node of the current selection. If they are text nodes (and disableSurrounding is not set or false), they are split at the current range's outer boundaries.
In the next step, the algorithm walks up to a common ancestor level which contains both the start and end node tree and adds all siblings to the node list. Afterwards, it determines which nodes are to be returned and which not, according to allowTextNodes and disableSurrounding.
2008/08/19 17:47
Technology

