I'm trying to get the start element and the end element of a selection and the offset of the selection in each, i do this in firefox as follows:
var delselection = window.getSelection();
var startOffset = delselection.anchorOffset;
var endOffset = delselection.focusOffset;
var startNode = delselection.anchorNode.parentNode;
var endNode = delselection.focusNode.parentNode;
However i have no idea how to do this in IE6, anyone able to point me in the right direction?
document.selection.
However the TextRange object returned by IE does not match Firefox/WebKit/W3's, and determining the exact positions of the start and end points is very frustrating. Depending on what exactly you are doing with the range you may be able to get somewhere with range.parentElement(), range.inRange() or range.compareEndPoints(). For rich text editors you will usually end up using the staggeringly ugly range.execCommand() interface.
The IE Range implementation is so odd and different to the Mozilla/Webkit/W3 model that you typically end up with completely different code paths for everything to do with selections between the two.
You should look at the ControlRange and TextRange objects of the IE BOM.
AnchorOffset,focusOffset and window.getSelection() are not supported by IE6/7 I believe.
If you know the object the selection is in (e.g., it's an input field the user is typing in that you want to change while they're typing), this code does the trick:
var selObj = null;
var selSave = null;
var selSaveEnd = null;
function SaveSelection(obj) {
if (obj.selectionStart) {
selObj = obj;
selSave = obj.selectionStart;
selSaveEnd = obj.selectionEnd;
}
else {
// Internet Explorer case
selSave = document.selection.createRange();
}
}
function RestoreSelection() {
if (selObj) {
selObj.focus();
selObj.selectionStart = selSave;
selObj.selectionEnd = selSaveEnd;
}
else {
// Internet Explorer case
selSave.select();
}
}